7.15 Performance Considerations
Writing efficient operator-heavy code — preferring set membership over list membership, ordering short-circuit conditions deliberately, and not sacrificing readability for cleverness.
Efficient Expressions
Prefer x in a_set over x in a_list for repeated membership checks on large collections (see 7.7 Membership Operators) — the operator looks identical, but the underlying cost differs by an order of magnitude at scale.
Short-Circuit Benefits
Order and/or conditions so the cheapest or most-likely-to-short-circuit check comes first — e.g. check a cheap flag before calling an expensive function in the same and expression.
# Better: cheap check first, expensive check only runs if needed
if user.is_active and user.has_expensive_permission_check():
...
Readability
A marginally “clever” one-liner that saves a few characters is rarely worth the readability cost — favor clear, parenthesized expressions over dense ones (see 7.17 Best Practices).
Quick Interview Answer
“Operator-level performance mostly comes down to two things: choosing the right container for membership tests —
set/dictfor O(1) average lookups instead of O(n) list scans — and orderingand/orconditions so cheap or likely-to-fail checks run first, letting short-circuit evaluation skip expensive work. Beyond that, a ‘clever’ dense expression rarely outperforms a readable one at runtime; the real cost of cleverness is almost always paid by whoever reads the code next.”
Common Mistakes
- Micro-optimizing operator choice in code that isn’t actually a bottleneck, at the cost of readability — profile first.
- Putting an expensive check first in an
and/orchain purely because it reads more naturally in that order, missing an easy short-circuit win.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form