Python 以开发效率著称,但运行速度常被诟病。实际上很多性能问题不是语言的锅,而是写法不够高效。本文用实测数据分享 6 个真正有效的优化方法。

1. 列表推导式 vs 循环 append

# 慢:循环 append
result = []
for x in range(100000):
    if x % 2 == 0:
        result.append(x * 2)

# 快:列表推导式
result = [x * 2 for x in range(100000) if x % 2 == 0]

实测:列表推导式快约 30%~50%,且更简洁。

2. 用生成器处理大数据

# 占内存:一次性生成 1000 万条
data = [process(x) for x in huge_list]

# 省内存:惰性求值
data = (process(x) for x in huge_list)
for item in data:
    consume(item)

当数据量超过内存时,生成器是唯一选择。

3. 优先用内置函数

# 慢:手写循环求和
total = 0
for x in data:
    total += x

# 快:内置 sum(C 实现)
total = sum(data)

sum、max、min、sorted 都是 C 实现,远快于 Python 层循环。

4. 字符串拼接用 join

# 慢:每次 + 都创建新字符串
s = ""
for word in words:
    s += word

# 快:join 一次性拼接
s = "".join(words)

5. 用 set 做成员检测

# 慢:list 成员检测 O(n)
if x in my_list: ...

# 快:set 成员检测 O(1)
my_set = set(my_list)
if x in my_set: ...

6. 用 cProfile 找到真正瓶颈

不要凭感觉优化,先 profiling:

import cProfile
cProfile.run("my_function()", sort="cumulative")

输出按累计时间排序,找到最耗时的函数再优化。

什么时候该上 C 扩展

如果热点函数确实是计算密集型(数值循环、图像处理),可以考虑:

原则:先让程序正确,再让它快。优化前先 profile,不要凭直觉。90% 的时间花在 10% 的代码上。