preallocate list

Bill Mill bill.mill at gmail.com
Wed Apr 13 09:16:37 EDT 2005


Just a correction:

<snip>
> I would profile your app to see that it's your append which is taking
> ages, but to preallocate a list of strings would look like:
> 
> ["This is an average length string" for i in range(approx_length)]
> 
> My guess is that it won't help to preallocate, but time it and let us
> know. A test to back my guess:
> 
> import timeit, math
> 
> def test1():
>     lst = [0 for i in range(100000)]
>     for i in xrange(100000):
>         lst[i] = math.sin(i) * i
> 
> def test2():
>     lst = []
>     for i in xrange(100000):
>         lst.append(math.sin(i) * i)
> 
> t1 = timeit.Timer('test1()', 'from __main__ import test1')
> t2 = timeit.Timer('test2()', 'from __main__ import test2')
> print "time1: %f" % t1.timeit(100)
> print "time2: %f" % t2.timeit(100)
> 

The results change slightly when I actually insert an integer, instead
of a float, with lst[i] = i and lst.append(i):

09:14 AM ~$ python test.py
time1: 3.352000
time2: 3.672000

The preallocated list is slightly faster in most of my tests, but I
still don't think it'll bring a large performance benefit with it
unless you're making a truly huge list.

I need to wake up before pressing "send".

Peace
Bill Mill



More information about the Python-list mailing list