Python Learning
⚡️ Python’s 1-Line Speed Booster: @lru_cache
👉 Did you know you can make slow Python functions run up to 100x faster by adding a single line of code?
Most tutorials skip functools.lru_cache, but it’s one of Python’s best built-in performance hacks.
🔹 How It Works
It automatically caches (remembers) the results of function calls. If you call the function with the same inputs again, Python skips the heavy computation and returns the saved answer instantly.
🔹 Code Comparison
❌ Slow (Re-calculates every single call):
def get_user_data(user_id):
# Imagine an expensive database query here
return fetch_from_db(user_id)
✅ Very Fast (Remembers previous results):
from functools import lru_cache
@lru_cache(maxsize=128)
def get_user_data(user_id):
# Only runs ONCE per unique user_id
return fetch_from_db(user_id)
🔹 Use It to:
✔️ Speedup repetitive API calls, math calculations, or DB queries.
✔️ No third-party libraries needed (built into Python's standard library).
✔️ Prevent unnecessary server load.
3 · 365 ·