Method much slower than function?

sjdevnull at yahoo.com sjdevnull at yahoo.com
Thu Jun 14 14:19:41 EDT 2007


On Jun 14, 1:12 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Thu, 14 Jun 2007 01:39:29 -0300, sjdevn... at yahoo.com
> <sjdevn... 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...

Are you using an old version of python?  I get a fairly small
difference between the 2:

Python 2.5 (r25:51908, Jan 23 2007, 18:42:39)
[GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on ELIDED
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> a=""
>>> 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)
...
>>> print timeit.Timer("f2()", "from __main__ import f2").repeat(number=1)
[0.91355299949645996, 0.86561012268066406, 0.84371185302734375]
>>> print timeit.Timer("f1()", "from __main__ import f1").repeat(number=1)
[0.94637894630432129, 0.89946198463439941, 1.170320987701416]




More information about the Python-list mailing list