Python 2.0b1 List comprehensions are slow
Robin Becker
robin at jessikat.fsnet.co.uk
Fri Sep 8 05:05:13 EDT 2000
In article <8p9ho7$4g0$1 at prometheus.acsu.buffalo.edu>, Kevin O'Connor
<koconnor at cse.buffalo.edu> writes
...
I get much the same results, but using dis the reason is obvious
ie the comprehensions are revealed as macros rather than a fast
operation
bar2/3
def bar2(arry):
return map(lambda x: x+12, arry)
def bar3(arry):
return [ x+12 for x in arry]
>>> dis(bar2)
0 SET_LINENO 1
3 SET_LINENO 2
6 LOAD_GLOBAL 0 (map)
9 LOAD_CONST 1 (<code object <lambda> at
0076BF60, file "<stdin>", line 2>)
12 MAKE_FUNCTION 0
15 LOAD_FAST 0 (arry)
18 CALL_FUNCTION 2
21 RETURN_VALUE
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
>>> dis(bar3)
0 SET_LINENO 1
3 SET_LINENO 2
6 BUILD_LIST 0
9 DUP_TOP
10 LOAD_ATTR 0 (append)
13 STORE_FAST 1 (__1__)
16 LOAD_FAST 0 (arry)
19 LOAD_CONST 1 (0)
>> 22 SET_LINENO 2
25 FOR_LOOP 20 (to 48)
28 STORE_FAST 2 (x)
31 LOAD_FAST 1 (__1__)
34 LOAD_FAST 2 (x)
37 LOAD_CONST 2 (12)
40 BINARY_ADD
41 CALL_FUNCTION 1
44 POP_TOP
45 JUMP_ABSOLUTE 22
>> 48 DELETE_FAST 1 (__1__)
51 RETURN_VALUE
52 LOAD_CONST 0 (None)
55 RETURN_VALUE
>>>
>
>First of all, the list comprehension feature has to be one of the NICEST
>features to be added to the language. After reading about it, and writing
>some test programs I was one step short of killing off all those ugly map
>and operator calls in all my old programs. The comprehensions are much
>easier to read than a mangled map setup, and they have the potential to be
>just as fast and significantly more flexible.
>
>Unfortunately, I'm a little concerned about the speed of the new list
>feature. According to the web site, "[a comprehension] is more efficient
>than map() with a lambda." However, this is not true in my test programs -
>they show comprehensions to be 50% slower than map with a lambda.
>
>I hope this can be resolved before 2.0 is released. :-)
>-Kevin
>
....
--
Robin Becker
More information about the Python-list
mailing list