Speed issues

Justin Sheehy dworkin at ccs.neu.edu
Tue Dec 28 10:19:23 EST 1999


Gerrit Holl <gerrit.holl at pobox.com> writes:

> is an assigment slower than appending to a list?

That isn't really the important question, given your example.

> def f(s):
>  o=[]
>  for c in s:
>   o.append(chr(ord(c)/2))
>  return string.join(o, '')
> 
> or:
> 
> def f(s):
>  o=''
>  for c in s:
>   o = o + chr(ord(c)/2) 
>  return o
> 
> What is faster? What do you prefer?

The first approach will generally be much faster, but the reason for
it is that the second approach will construct and throw away so many
temporary strings along the way.

Each time the line 

  o = o + chr(ord(c)/2)  

Is processed, a new, slightly larger string is built and the previous
one is thrown away.  The first approach does not have this problem.

-Justin

 



More information about the Python-list mailing list