Method much slower than function?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Thu Jun 14 01:12:31 EDT 2007
En Thu, 14 Jun 2007 01:39:29 -0300, sjdevnull at yahoo.com
<sjdevnull at yahoo.com> 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...
--
Gabriel Genellina
More information about the Python-list
mailing list