Possible memory leak?
Fredrik Lundh
fredrik at pythonware.com
Wed Jan 25 16:43:02 EST 2006
Giovanni Bajo wrote:
> ------- foo.py -----
> def iters(n):
> s = ''
> for i in xrange(n):
> s += chr(i%64)
> return s
>
> def iters2(n):
> L = []
> for i in xrange(n):
> L.append(chr(i%64))
> return "".join(L)
> ------- foo.py -----
>
> So, look, it's even faster than the solution you're proposing.
since you know the length, you can preallocate the list
def iters3(n):
L = [None]*n
for i in xrange(n):
L[i] = chr(i%64)
return "".join(L)
or use a preallocated array
def iters4(n):
L = array.array("B", [0])*n
for i in xrange(n):
L[i] = i%64
return L.tostring()
on my machine, the last one is twice as fast as your "even faster"
solution under 2.4. in earlier versions, it's just under 5 times faster.
for the OP's problem, a PIL-based solution would probably be ~100
times faster than the array solution, but that's another story.
</F>
More information about the Python-list
mailing list