[issue32856] Optimize the `for y in [x]` idiom in comprehensions

Serhiy Storchaka report at bugs.python.org
Fri Feb 16 12:31:57 EST 2018


Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:

Here are some microbenchmarks. But since this code always is a part of complex expression it may be not make sense to talk about its pure speed.

$ ./python -m timeit -s 'a = list(range(1000))' -- '[y for x in a for y in [x]]'
Unpatched:  5000 loops, best of 5: 81.4 usec per loop
Patched:   10000 loops, best of 5: 19.8 usec per loop

For comparison the variant without temporary variable:

$ ./python -m timeit -s 'a = list(range(1000))' -- '[x for x in a]'
20000 loops, best of 5: 15.6 usec per loop

The overhead of using temporary variable is decreased from 66 usec to 4.2 usec (by 16 times).

In more realistic examples the subexpression assigned to temporary variable is slow. Otherwise it would be not worth to use a temporary variable. Therefore the relative speed up of the whole comprehension expression caused by this optimization is much smaller.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32856>
_______________________________________


More information about the Python-bugs-list mailing list