Reputation: 2516
In the below 2 cases, which one is more efficient?
Case 1:
def test(x):
hello(x)
def hello(y):
return world(y)
def world(z):
return z
Case 2:
def test(x):
a = hello(x)
def hello(y)
b = world(y)
return b
def world(z):
c = z
return z
Upvotes: 0
Views: 64
Reputation: 50453
TL;DR: both are just as fast.
Here are the timings on my machine with the CPython 3.7.6 interpreter (on a loop of 10000000 run repeated 3 times):
First case: 109 ns
Second case: 111 ns
The difference is negligible between the two. Thus, the two are as fast.
Using PyPy (JIT-based interpreter), the JIT compiler is able to optimize both cases and remove all the function calls. Thanks to the JIT, the code can be executed at a zero cost and the time of the two cases is thus exactly the same.
If you use Cython the same kind of things could occur.
Advice:
Please do not tweak a Python code with micro-optimizations like this for better performance. Readability takes precedence over performance in Python.* If you really care about performance of such a thing, please use an alternative interpreter like PyPy or Cython or an integrated Python JIT compiler (such as Numba).
Upvotes: 2