[Python-Dev] identity operands (was python-dev Summary for 2005-03-01 through 2005-03-15 [draft]) (original) (raw)

Timothy Fitz firemoth at gmail.com
Sun Mar 20 21:09:47 CET 2005


[Nick Coghlan]

So, using "".join is roughly three times as fast as abusing sum :)

True in the case where you're concatenating three strings, but what about 100 strings?

(Full source attached) Py> timeit.Timer("sum(strings, ai)", setup).repeat() [33.553668413164239, 32.861660909417253, 33.092705357803851] Py> timeit.Timer("''.join(strings)", setup).repeat() [5.4385152302876492, 5.3633637794747671, 5.3587657090496066] Py> timeit.Timer(" + ".join('"' + s + '"' for s in strings), "").repeat() [17.726616371633828, 17.785511845779279, 18.179861127601413]

So at 100 strings, the difference is over 5x, and I assume you'll see the relative distance increase as you increase the number of strings.

Timothy Fitz -------------- next part -------------- import timeit from random import choice from random import randrange from string import uppercase

setup = """ class additive_identity(object): def add(self, other): return other

ai = additive_identity()

from random import choice from random import randrange from string import uppercase strings = ["".join(choice(uppercase) for i in range(randrange(10))) for i in range(100)]"""

strings = ["".join(choice(uppercase) for i in range(randrange(10))) for i in range(100)]

print "SUM:", timeit.Timer("sum(strings, ai)", setup).repeat() print "JOIN:", timeit.Timer("''.join(strings)", setup).repeat() print "ADD:", timeit.Timer(" + ".join('"' + s + '"' for s in strings), "").repeat()



More information about the Python-Dev mailing list