1

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?

6
  • 1
    test1 and test2 are equivalent in terms of bytecode Commented Sep 1, 2016 at 9:26
  • @vaultah: so 1,2,3 is also a tuple? Commented Sep 1, 2016 at 9:27
  • @Jean-FrançoisFabre yes it is. Commented Sep 1, 2016 at 9:28
  • @Jean-FrançoisFabre in this case, yes. Commented Sep 1, 2016 at 9:28
  • 4
    The commas make a tuple, not the parenthesis. Commented Sep 1, 2016 at 9:48

1 Answer 1

8

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
>>>
Sign up to request clarification or add additional context in comments.

4 Comments

Did you re-run the test to verify?
@ReutSharabani yes, and results on my machine is super noisy. I get runs where test1 execution time is about test2 execution time, runs where test1 is longer than test2, runs where test2 is longer than test1. It's kind of expected where you have anything running in background and try to profile something that's super quick to execute.
ok, cause my runs were also inconsistent but don't have an environment to test in thats not loaded at the moment.
@ReutSharabani The syntax for creating tuples are the commas, the parenthesis are optional. So writing x = 1,2,3 creates the tuple (1,2,3) exactly in the same way as writing x = (1,2,3). The only difference occurs during parsing, but as shown in this answer the interpreter does exactly the same things in both cases. Now, given that the operations you are profiling are so fast it's expected that you'll see big difference during different runs. Try to run the test for test1 multiple times and you'll see the timings wander off quite a bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.