A problem about Python function max() and ifelse structure time consuming

Viewed 48

If I want to compare two number in python:

One way is by max():

r = max(r,a-b)

the other way is in this way:

r = a-b if a-b>r else r

And the second way is faster than the first way, this performance puzzles me a lot. Because the max() function must have been optimized, and the second way may compute (a-b) for two times, I think. Could anyone explain me why?

1 Answers

The overhead with using max is that this will invoke a function call. Every function call comes with this overhead. Modern compilers tend to optimize this by (optionally) making the function calls inline, that is by replacing the function code right in the place where it is called. Even though python built-ins are optimized, there is still some overhead with argument parsing.

Related