- String 3: the argument string is modified but NOT passed back to
the caller;
- String 4: the argument string is passed "by reference" within a
list object and modified.
i think this informations are very interesting
thanks!
greetings
iolo
------------ CODE -------------
import sys
from string import *
from time import *
def ls(str):
return len(str)
def ll(str):
return len(str[0])
def as(str):
str += "x"
return len( str )
def al(str):
str[0] += "x"
return len( str[0] )
loop = 2000
strlen = 30000
strl = []
strl.append("")
strs = ""
for a in range(strlen):
strs += 'x'
strl[0] += 'y'
print "Loop: ", loop
print "Stringlength: " , strlen
print
print 'String 1'
l = 0
start = time()
for x in range(loop):
l += ls(strs)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if strlen == l / loop:
print 'OK'
else:
print 'ERROR'
print
print 'String 2'
l = 0
start = time()
for x in range(loop):
l += ll(strl)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if strlen == l / loop:
print 'OK'
else:
print 'ERROR'
print
print 'String 3'
l = 0
start = time()
for x in range(loop):
l += as(strs)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if l == loop * strlen + loop:
print 'OK'
else:
print 'ERROR'
print
print 'String 4'
l = 0
start = time()
for x in range(loop):
l += al(strl)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if l == (loop / 2 ) * ((strlen + 1) + (strlen + loop)):
print 'OK'
else:
print 'ERROR'
---------------- RESULT ----------------
Loop: 50000
Stringlength: 200000
String 1
duration in seconds: 0.0620000362396
result: 10000000000
OK
String 2
duration in seconds: 0.0779999494553
result: 10000000000
OK
String 3
duration in seconds: 3.2349998951
result: 10000050000
OK
String 4
duration in seconds: 5.93700003624
result: 11250025000
OK
--------------------------------------------------
The text of the string is not copied; a reference to the string/object
is passed into the function. You can modify objects passed into
functions (but only if they're mutable--strings and integers are
examples of immutable objects), but you cannot rebind the variable
holding the value in the caller's scope.
There have been some discussions in this newsgroup about whether
Python is call-by-value or not. I'm not sure if I want to recommend
looking for them; there was no good consensus about the terminology.