Back
+15 XP
Concept

Optimization: Local Variable Lookup vs Global Scope

Local variables are stored in an array indexed by integer offsets (`LOAD_FAST`). Globals require dictionary hash table lookups (`LOAD_GLOBAL`). Caching globals locally accelerates tight loops 🏎️.

python
import math

# Slower: Every loop iteration does a global dictionary lookup for math.sin
# def slow():
#     return [math.sin(i) for i in range(1000)]

# Faster: Cache global into local variable (LOAD_FAST)
def fast():
    sin = math.sin  # Local reference 🏎️
    return [sin(i) for i in range(5)]

print(fast())

# 89. Optimization: Local Variable Lookup vs Global Scope Local variables are stored in an array indexed by integer offsets (`LOAD_FAST`). Globals require dictionary hash table lookups (`LOAD_GLOBAL`). Caching globals locally accelerates tight loops 🏎️. ```python import math # Slower: Every loop iteration does a global dictionary lookup for math.sin # def slow(): # return [math.sin(i) for i in range(1000)] # Faster: Cache global into local variable (LOAD_FAST) def fast(): sin = math.sin # Local reference 🏎️ return [sin(i) for i in range(5)] print(fast()) ``` `LOAD_FAST` reads directly from a fixed C array offset inside the function stack frame. `LOAD_GLOBAL` must search `globals()` and then `builtins()` hash maps! 🏎️ --- ### Question Why are local variable lookups faster than global variable lookups in Python? 🧠 - [ ] a. Locals are resolved via fast C array indices (`LOAD_FAST`) instead of dictionary hash lookups 🏎️ - [ ] b. Globals are stored on secondary disk storage - [ ] c. CPython deletes globals after every function call - [ ] d. Local variables bypass CPU cache lines completely --- ### Challenge Write a function `sum_fast(numbers)` that binds local `local_sum = sum` and returns `local_sum(numbers)`. Print `sum_fast([10, 20, 30])`. 🎯 <details> <summary>Solution</summary> ```python def sum_fast(numbers): local_sum = sum return local_sum(numbers) print(sum_fast([10, 20, 30])) ``` </details>

Checkpoint

Why are local variable lookups faster than global variable lookups in Python? 🧠

Practice

Write a function `sum_fast(numbers)` that binds local `local_sum = sum` and returns `local_sum(numbers)`. Print `sum_fast([10, 20, 30])`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks