Python Performance Tips: Make Your Code 10x Faster

python dev.to

Python Performance Tips: Make Your Code 10x Faster

Speed matters. Here are the most impactful Python optimizations.

1. Use Built-in Functions

# Slow
total = 0
for n in numbers:
    total += n

# Fast - use built-ins
total = sum(numbers)
Enter fullscreen mode Exit fullscreen mode

2. List Comprehensions Over Loops

# Slow
squares = []
for x in range(1000):
    squares.append(x ** 2)

# Fast
squares = [x ** 2 for x in range(1000)]

# Fastest for large data - generator
squares_gen = (x ** 2 for x in range(1000000))
Enter fullscreen mode Exit fullscreen mode

3. Use Sets for Membership Testing

# Slow - O(n) for list
items_list = [1, 2, 3, ...]
if 999 in items_list:  # searches entire list

# Fast - O(1) for set
items_set = {1, 2, 3, ...}
if 999 in items_set:  # instant lookup
Enter fullscreen mode Exit fullscreen mode

4. String Concatenation

# Slow - creates new string each iteration
result = ""
for s in strings:
    result += s

# Fast - join is O(n)
result = "".join(strings)
Enter fullscreen mode Exit fullscreen mode

5. Cache with lru_cache

from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2: return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(100))  # Instant after first call
Enter fullscreen mode Exit fullscreen mode

6. Use numpy for Numerical Operations

import numpy as np

# Python list - slow
result = [x * 2 for x in range(1000000)]

# numpy - 100x faster
arr = np.arange(1000000)
result = arr * 2
Enter fullscreen mode Exit fullscreen mode

7. Avoid Global Variables

# Slow - global lookup each iteration
count = 0
def slow():
    global count
    for i in range(1000000):
        count += i

# Fast - local variable
def fast():
    count = 0
    for i in range(1000000):
        count += i
    return count
Enter fullscreen mode Exit fullscreen mode

8. Profile Before Optimizing

import cProfile
cProfile.run('your_function()', sort='cumulative')
Enter fullscreen mode Exit fullscreen mode

Follow me for more Python performance tips! 🐍

Follow for more Python content!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $30*

Source: dev.to

arrow_back Back to Tutorials