Python Performance Optimization Tips: Local Variables, Reduced Function Calls, Generators, and More
This article presents practical Python performance optimization techniques—including using local variables, minimizing function calls, pre‑computing loop conditions, preferring direct iteration, employing generator expressions, compiling code objects, and structuring modules—to improve speed and reduce memory usage.
Master some techniques to improve Python program performance and avoid unnecessary resource waste.
1. Use local variables – Prefer local over global variables to enhance maintainability, speed, and memory usage. For example, replace os.linesep with a short local alias like ls = os.linesep .
2. Reduce function call count – When checking object types, isinstance() is fastest, followed by identity comparison ( id() ), and finally type() . Example:
<code># 判断变量 num 是否为整数类型
type(num) == type(0) # 调用三次函数
type(num) is type(0) # 身份比较
isinstance(num, (int)) # 调用一次函数</code>Avoid repeating expensive operations in loop conditions; compute them once before the loop:
<code># 每次循环都需要重新执行 len(a)
while i < len(a):
statement
# len(a) 仅执行一次
m = len(a)
while i < m:
statement</code>Import specific objects directly to skip an extra attribute lookup:
Use from X import Y instead of import X; X.Y .
3. Use mapping instead of conditional search – Dictionary lookups are faster than if chains. Example:
<code># dict 查找,性能更优
d = {1:10, 2:20, ...}
b = d[a]</code>4. Iterate directly over sequence elements – Looping over items is faster than looping over indices:
<code>a = [1,2,3]
for item in a:
print(item)
# vs
for i in range(len(a)):
print(a[i])</code>5. Use generator expressions instead of list comprehensions – Generators produce items lazily, saving memory. Example:
<code># 生成器表达式
l = sum(len(word) for line in f for word in line.split())
# 列表解析(会创建完整列表)
l = sum(len(word) for line in f for word in line.split())</code>6. Compile before calling – Compile code strings with compile() and execute the code object, and compile regular expressions with re.compile() to avoid repeated compilation.
7. Module programming habits – Place executable code inside functions (e.g., main() ) and guard with if __name__ == "__main__": to prevent unwanted execution on import.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.