Python: multiple assignment vs. individual assignment speed

I've been looking to squeeze a little more performance out of my code; recently, while browsing this Python wiki page, I found this claim:

Multiple assignment is slower than individual assignment. For example "x,y=a,b" is slower than "x=a; y=b".

Curious, I tested it (on Python 2.7):

$ python -m timeit "x, y = 1.2, -1.4"
10000000 loops, best of 3: 0.0365 usec per loop

$ python -m timeit "x = 1.2" "y = -1.4"
10000000 loops, best of 3: 0.0542 usec per loop

I repeated several times, in different orders, etc., but the multiple assignment snippet consistently performed at least 30% better than the individual assignment. Obviously the parts of my code involving variable assignment aren't going to be the source of any significant bottlenecks, but my curiousity is piqued nonetheless. Why is multiple assignment apparently faster than individual assignment, when the documentation suggests otherwise?

EDIT:

I tested assignment to more than two variables and got the following results:

The trend seems more or less consistent; can anyone reproduce it?

(CPU: Intel Core i7 @ 2.20GHz)


Interestingly, it may depend on the CPU to some extent. These are both 64 bit linux machines (same Python build).

Result for Intel(R) Core(TM)2 Duo CPU T7300 @ 2.00GHz

$ python -V
Python 2.7.5+
$ python -m timeit "x, y = 1.2, -1.4"
10000000 loops, best of 3: 0.0554 usec per loop
$ python -m timeit "x = 1.2" "y = -1.4"
10000000 loops, best of 3: 0.0349 usec per loop

Result for Intel(R) Pentium(R) CPU G850 @ 2.90GHz

$ python -V
Python 2.7.5+
$ python -m timeit "x, y = 1.2, -1.4"
10000000 loops, best of 3: 0.0245 usec per loop
$ python -m timeit "x = 1.2" "y = -1.4"
10000000 loops, best of 3: 0.0394 usec per loop

Better look at dis module of python. Which disassembles bytecode. The test shows on two variable assignment:

import dis 

def single_assignment():
    x = 1 
    y = 2 

def multiple_assignment():
    x, y = 1, 2

print dis.dis(single_assignment)
print dis.dis(multiple_assignment)

Bytecode:

  4           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (x)

  5           6 LOAD_CONST               2 (2)
              9 STORE_FAST               1 (y)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE        
None
  8           0 LOAD_CONST               3 ((1, 2))
              3 UNPACK_SEQUENCE          2
              6 STORE_FAST               0 (x)
              9 STORE_FAST               1 (y)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE        
None

It looks number of bytecode required is same in case of 2 variables. If there's 3 or more variable assignment, number of bytecode is smaller.

链接地址: http://www.djcxy.com/p/19416.html

上一篇: 检测与圆圈类似的对象

下一篇: Python:多任务与个人分配速度