[Python-ideas] Length hinting and preallocation for container types

Andrew Barnert abarnert at yahoo.com
Tue Mar 5 21:42:03 CET 2013


> From: Christian Heimes <christian at python.org>

> 
> Am 05.03.2013 18:10, schrieb Antoine Pitrou:
>>  So how about benchmark numbers?
> 
> The speedup is smallish:
> 
> $ ./python -m timeit -n1000 "l = []" 
> "l.__preallocate__(10000)" "app =
> l.append" "for i in range(10000): app(i)" 
> "l.__shrink__()"
> 1000 loops, best of 3: 3.68 msec per loop
> 
> $ ./python -m timeit -n1000 "l = []" "app = l.append" 
> "for i in
> range(10000): app(i)"
> 1000 loops, best of 3: 3.75 msec per loop


So, that's a 1.8% speedup. While doing things right gives a 20% speedup:

$ python3.3 -m timeit -n1000 "l=[]" "app = l.append" "for i in range(10000): app(i)"
1000 loops, best of 3: 557 usec per loop
$ python3.3 -m timeit -n1000 "l = [i for i in range(10000)]"
1000 loops, best of 3: 447 usec per loop

Or (but obviously this isn't generally applicable):

$ python3.3 -m timeit -n1000 "l = list(range(10000))"
1000 loops, best of 3: 236 usec per loop



More information about the Python-ideas mailing list