W3docs

Why does Python code run faster in a function?

Python code can run faster in a function because of something called "Just-In-Time" (JIT) compilation.

Python code often runs faster inside a function than at the module level in standard CPython due to how the interpreter handles variable lookups. When code runs at the module level, variables are stored in the global namespace, and accessing them requires LOAD_GLOBAL bytecode instructions, which involve dictionary lookups. Inside a function, local variables are stored in a fast array and accessed with LOAD_FAST, which is significantly quicker. Additionally, functions reduce the overhead of global namespace lookups and allow the interpreter to optimize execution. (Note: PyPy uses Just-In-Time (JIT) compilation, which further accelerates repeated function calls, but standard CPython relies on bytecode optimization and local variable caching.)

Here's an example of a simple function in Python:

A simple function in Python

def add_numbers(a, b):
    return a + b

result = add_numbers(3, 4)
print(result)

In this example, the add_numbers function is defined and then called with the arguments 3 and 4. The function takes these two numbers, adds them together, and returns the result, which is then printed to the console. When the function is called, the Python interpreter uses optimized local variable lookups (LOAD_FAST) instead of slower global lookups, reducing execution overhead.

To verify this performance difference, you can run a quick benchmark comparing module-level code to function-level code:

import timeit

# Module-level execution
x = 10
y = 20
global_time = timeit.timeit("x + y", globals=globals(), number=1000000)

# Function execution
def add_numbers(a, b):
    return a + b
local_time = timeit.timeit("add_numbers(10, 20)", globals=globals(), number=1000000)

print(f"Global: {global_time:.4f}s")
print(f"Local:  {local_time:.4f}s")

This benchmark demonstrates that local variable access inside a function is consistently faster than global access in standard CPython.