Search code examples
pythonmax

Why is max() function so much slower when comparing 2 elements vs direct comparison with an if statement?


By running the below code I get for direct comparison with an if statement almost 4x the speed vs using the max function.

I am trying to understand the reason behind this.

comparison : 0.63s, max : 2.3s

import time

if _name_ == '_main_':
    sim = 10**7

    s = time.time()
    for _ in range(sim):
        if 1 > 2:
            pass
    res1 = time.time()-s

    s = time.time()
    for _ in range(sim):
        max(1, 2)
    res2 = time.time()-s

    print('comparison : {:.2}s, max : {:.2}s'.format(res1, res2))

Solution

  • because max involves a dictionary lookup for the function name, then a function call, whereas direct < operator does not.

    max is beginning to become interesting speed-wise when you have more elements.

    Related / same speed difference: