best-practices
Loop Optimisation Guide
How to write loops that compile to the fastest machine code.
Published May 30, 2026
Unroll Small Loops
for i in range(0, len(data), 4):
a = data[i]; b = data[i+1]; c = data[i+2]; d = data[i+3]Avoid Function Calls in Loops
# Bad
for x in data:
result.append(math.sqrt(x))
# Good
from math import sqrt
for x in data:
result.append(sqrt(x))Use Range Instead of While
for i in range(n): # compiles better
...