jia yin
jia yin

Reputation: 29

Why it is faster to return a tuple than multiple values in Python?

I did a small test:

In [12]: def test1():
    ...:     return 1,2,3
    ...: 

In [13]: def test2():
    ...:     return (1,2,3)
    ...: 

In [14]: %timeit a,b,c = test1()

The slowest run took 66.88 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 92.7 ns per loop

In [15]: %timeit a,b,c = test2()

The slowest run took 74.43 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 80.1 ns per loop

Returning a tuple is about 15% faster than returning multiple values. Why is it so?

Upvotes: 1

Views: 458

Answers (1)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

Both test1 and test2 results in same bytecode, so they have to perform in same speed. Your measurement conditions wasn't consistent (e.g. CPU load was increased for test2, due to additional background processes).

>>> import dis
>>> def test1():
...     return 1,2,3
...
>>> def test2():
...     return (1,2,3)
...
>>> dis.dis(test1)
  2           0 LOAD_CONST               4 ((1, 2, 3))
              3 RETURN_VALUE
>>> dis.dis(test2)
  2           0 LOAD_CONST               4 ((1, 2, 3))
              3 RETURN_VALUE
>>>

Upvotes: 8

Related Questions