Skip to content

MemoryError

错误信息

                MemoryError
              

快速摘要

你的 program tried 到 allocate 更多 memory than 是 available.

为什么发生

  • 创建 very 大列表 or 数据结构

  • 加载 huge file 完全到 memory

  • 无限 recursion or unbounded 数据 growth

  • Memory leak 从 accumulating 引用

最小示例

✗ 错误代码
# Trying to create a huge list
big_list = [0] * 10**12  # MemoryError
✓ 修复代码
# Use a generator instead of a list
def zeros(n):
    for _ in range(n):
        yield 0

# Process one at a time, minimal memory
for z in zeros(10**12):
    pass  # Process each zero

相反的 创建 huge 列表 in memory, use generator 那个 produces 值 one at 时间.

如何诊断

  • 检查大小的 数据结构是 创建

  • Monitor memory usage 使用 tools 如 memory_profiler

  • Look for unbounded 循环 or growing 集合

如何修复

  • 处理数据 in 块相反的 加载一切 at 一次

  • Use generators for lazy evaluation

  • Free unused 引用 (del 变量, gc.collect())

  • Use 更多 memory-efficient 数据结构

如何预防

  • Use generators and iterators for 大 datasets

  • 处理 files 行通过行 相反的 读取所有 at 一次

  • Monitor memory usage in production

相关资源

相关术语

相关课程

← 返回语言