-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 07/14/2011 11:47 AM, Tres Seaver wrote:
While we're at it, 'list.insert(0,foo)' is known to be slower in a tight loop than 'list.append(foo)', with a 'reversed' at the end of the loop::
$ python -m timeit -s "from string import letters" "path = []" \ "for letter in letters: path.append(letter)" \ "result = tuple(reversed(path))" 100000 loops, best of 3: 15.9 usec per loop
$ python -m timeit -s "from string import letters" "path = []" \ "for letter in letters: path.insert(0, letter)" \ "result = tuple(path)" 10000 loops, best of 3: 25.3 usec per loop
For the sake of comparison, the original tuple addition is actually between the two:
$ python -m timeit -s "from string import letters" "result = ()" \ "for letter in letters: result += (letter,)" 10000 loops, best of 3: 21.6 usec per loop
A further micro-optimization is to pre-allocate a big list in a thread local. Running the attached script produces:: $ python perftest.py Via insert_0: 24.8401839733 Via append: 15.6596238613 speedup: 37.0% Via tuple_add: 21.9555268288 speedup: 11.6% Via prealloc: 10.5278339386 speedup: 57.6% Tres. - -- =================================================================== Tres Seaver +1 540-429-0999 tseaver@palladion.com Palladion Software "Excellence by Design" http://palladion.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAk4fIVAACgkQ+gerLs4ltQ6BlACguSHcHLWGjVIVJlQYIpL42RNc mqMAn1Y16tyVmUkxd2ipNrZSeZpSFVEA =oJJY -----END PGP SIGNATURE-----