Python程序如何进行内存优化?
进阶Python
答题要点
import sys
from pympler import asizeof
# 查看对象内存
data = [1, 2, 3]
print(sys.getsizeof(data)) # 浅层大小
print(asizeof.asizeof(data)) # 深层大小
# __slots__减少实例内存
class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
# 生成器代替列表
# 不好
squares = [x**2 for x in range(1000000)]
# 好
squares = (x**2 for x in range(1000000))
# numpy数组代替列表
import numpy as np
# Python列表:每个元素是对象,额外开销大
py_list = [1.0] * 1000000 # ~8MB + 对象开销
# NumPy数组:连续内存,类型固定
np_array = np.ones(1000000) # ~8MB
# 字符串驻留
import sys
s1 = sys.intern('frequently_used_string')
# 对象池复用
class ObjectPool:
def __init__(self, factory, size=100):
self.pool = [factory() for _ in range(size)]
def acquire(self):
return self.pool.pop() if self.pool else factory()
def release(self, obj):
self.pool.append(obj)
# pandas内存优化
df['category_col'] = df['category_col'].astype('category')
df['int_col'] = pd.to_numeric(df['int_col'], downcast='integer')
# 垃圾回收控制
import gc
gc.collect() # 强制回收
gc.disable() # 禁用自动GC(需谨慎)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题