Why it is so dramatical?
Christopher A. Craig
list-python at ccraig.org
Tue Sep 3 01:04:45 EDT 2002
djw <dwelch91 at nospam.attbi.com> writes:
> Stupid question:
>
> If ""join() is 100-1000 X faster, why doesn't the Python interperter
> translate s = s1 + s2 + ... into s = "".join( [ s1, s2, ... ] )
> automatically?
You won't see that kind of dramatic results if you did that. In fact,
my testing shows it would be slower.
s = "".join(s1, s2) is slower than s=s1+s2. The reason you see that
kind of speed up is that list.append(s1) is a ton faster than s+=s1,
and "".join() is moved outside the loop. Compare the following
(presume 'a' contains some string):
method a)
s=""
for x in xrange(10000):
s += a
method b)
l = []
for x in xrange(10000):
l.append(a)
s = "".join(l)
method c)
s=""
for x in xrange(10000):
s = "".join([s, a])
method a creates 10,000 individual string objects
method b creates 1 list object (with a bunch of appends) and 1 string
object
method c creates 10,000 list objects (each of two elements s and a) and
10,000 string objects.
On my system, as I would expect, method a takes about .40 seconds,
method b takes .048, and method c takes .51.
--
Christopher A. Craig <list-python at ccraig.org>
"Imagination is more important than knowledge" Albert Einstein
More information about the Python-list
mailing list