Gabriel Genellina wrote: > En Thu, 14 Jun 2007 01:39:29 -0300, [EMAIL PROTECTED] > <[EMAIL PROTECTED]> escribió: > >> Gabriel Genellina wrote: >>> In addition, += is rather inefficient for strings; the usual idiom is >>> using ''.join(items) >> >> Ehh. Python 2.5 (and probably some earlier versions) optimize += on >> strings pretty well. >> >> a="" >> for i in xrange(100000): >> a+="a" >> >> and: >> >> a=[] >> for i in xrange(100000): >> a.append("a") >> a="".join(a) >> >> take virtually the same amount of time on my machine (2.5), and the >> non-join version is clearer, IMO. I'd still use join in case I wind >> up running under an older Python, but it's probably not a big issue >> here. > > Yes, for concatenating a lot of a's, sure... Try again using strings > around the size of your expected lines - and make sure they are all > different too. > > py> import timeit > py> > py> def f1(): > ... a="" > ... for i in xrange(100000): > ... a+=str(i)*20 > ... > py> def f2(): > ... a=[] > ... for i in xrange(100000): > ... a.append(str(i)*20) > ... a="".join(a) > ... > py> print timeit.Timer("f2()", "from __main__ import f2").repeat(number=1) > [0.42673663831576358, 0.42807591467630662, 0.44401481193838876] > py> print timeit.Timer("f1()", "from __main__ import f1").repeat(number=1) > > ...after a few minutes I aborted the process...
I can't confirm this. $ cat join.py def f1(): a = "" for i in xrange(100000): a += str(i)*20 def f2(): a = [] for i in xrange(100000): a.append(str(i)*20) a = "".join(a) def f3(): a = [] append = a.append for i in xrange(100000): append(str(i)*20) a = "".join(a) $ python2.5 -m timeit -s 'from join import f1' 'f1()' 10 loops, best of 3: 212 msec per loop $ python2.5 -m timeit -s 'from join import f2' 'f2()' 10 loops, best of 3: 259 msec per loop $ python2.5 -m timeit -s 'from join import f3' 'f3()' 10 loops, best of 3: 236 msec per loop Peter -- http://mail.python.org/mailman/listinfo/python-list