← 返回
未分类 中文

memory-optimization

Optimize Python code for reduced memory usage and improved memory efficiency. Use when asked to reduce memory footprint, fix memory leaks, optimize data stru...
优化 Python代码,降低内存使用并提升内存效率。适用于需要减少内存占用、修复内存泄漏、优化数据结构等场景。
lnj22 lnj22 来源
未分类 clawhub v0.1.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 343
下载
💾 0
安装
1
版本
#latest

概述

Memory Optimization Skill

Transform Python code to minimize memory usage while maintaining functionality.

Workflow

  1. Profile to identify memory bottlenecks (largest allocations, leak patterns)
  2. Analyze data structures and object lifecycles
  3. Select optimization strategies based on access patterns
  4. Transform code with memory-efficient alternatives
  5. Verify memory reduction without correctness loss

Memory Optimization Decision Tree

What's consuming memory?

Large collections:
├── List of objects → __slots__, namedtuple, or dataclass(slots=True)
├── List built all at once → Generator/iterator pattern
├── Storing strings → String interning, categorical encoding
└── Numeric data → NumPy arrays instead of lists

Data processing:
├── Loading full file → Chunked reading, memory-mapped files
├── Intermediate copies → In-place operations, views
├── Keeping processed data → Process-and-discard pattern
└── DataFrame operations → Downcast dtypes, sparse arrays

Object lifecycle:
├── Objects never freed → Check circular refs, use weakref
├── Cache growing unbounded → LRU cache with maxsize
├── Global accumulation → Explicit cleanup, context managers
└── Large temporary objects → Delete explicitly, gc.collect()

Transformation Patterns

Pattern 1: Class to __slots__

Reduces per-instance memory by 40-60%:

Before:

class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

After:

class Point:
    __slots__ = ('x', 'y', 'z')

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

Pattern 2: List to Generator

Avoid materializing entire sequences:

Before:

def get_all_records(files):
    records = []
    for f in files:
        records.extend(parse_file(f))
    return records

all_data = get_all_records(files)
for record in all_data:
    process(record)

After:

def get_all_records(files):
    for f in files:
        yield from parse_file(f)

for record in get_all_records(files):
    process(record)

Pattern 3: Downcast Numeric Types

Reduce NumPy/Pandas memory by 2-8x:

Before:

df = pd.read_csv('data.csv')  # Default int64, float64

After:

def optimize_dtypes(df):
    for col in df.select_dtypes(include=['int']):
        df[col] = pd.to_numeric(df[col], downcast='integer')
    for col in df.select_dtypes(include=['float']):
        df[col] = pd.to_numeric(df[col], downcast='float')
    return df

df = optimize_dtypes(pd.read_csv('data.csv'))

Pattern 4: String Deduplication

For repeated strings:

Before:

records = [{'status': 'active', 'type': 'user'} for _ in range(1000000)]

After:

import sys

STATUS_ACTIVE = sys.intern('active')
TYPE_USER = sys.intern('user')

records = [{'status': STATUS_ACTIVE, 'type': TYPE_USER} for _ in range(1000000)]

Or with Pandas:

df['status'] = df['status'].astype('category')

Pattern 5: Memory-Mapped File Processing

Process files larger than RAM:

import mmap
import numpy as np

# For binary data
with open('large_file.bin', 'rb') as f:
    mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    # Process chunks without loading entire file

# For NumPy arrays
arr = np.memmap('large_array.dat', dtype='float32', mode='r', shape=(1000000, 100))

Pattern 6: Chunked DataFrame Processing

def process_large_csv(filepath, chunksize=10000):
    results = []
    for chunk in pd.read_csv(filepath, chunksize=chunksize):
        result = process_chunk(chunk)
        results.append(result)
        del chunk  # Explicit cleanup
    return pd.concat(results)

Data Structure Memory Comparison

StructureMemory per itemUse case
-------------------------------------
list of dict~400+ bytesFlexible, small datasets
list of class~300 bytesObject-oriented, small
list of __slots__ class~120 bytesMany similar objects
namedtuple~80 bytesImmutable records
numpy.ndarray8 bytes (float64)Numeric, vectorized ops
pandas.DataFrame~10-50 bytes/cellTabular, analysis

Memory Leak Detection

Common leak patterns and fixes:

PatternCauseFix
---------------------
Growing cacheNo eviction policy@lru_cache(maxsize=1000)
Event listenersNot unregisteredWeak references or explicit removal
Circular referencesObjects reference each otherweakref, break cycles
Global listsAppend without cleanupBounded deque, periodic clear
ClosuresCapture large objectsCapture only needed values

Profiling Commands

# Object size
import sys
sys.getsizeof(obj)  # Shallow size only

# Deep size with pympler
from pympler import asizeof
asizeof.asizeof(obj)  # Includes referenced objects

# Memory profiler decorator
from memory_profiler import profile
@profile
def my_function():
    pass

# Tracemalloc for allocation tracking
import tracemalloc
tracemalloc.start()
# ... code ...
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

Verification Checklist

Before finalizing optimized code:

  • [ ] Memory usage reduced (measure with profiler)
  • [ ] Functionality preserved (same outputs)
  • [ ] No new memory leaks introduced
  • [ ] Performance acceptable (generators may add iteration overhead)
  • [ ] Code remains readable and maintainable

版本历史

共 1 个版本

  • v0.1.0 当前
    2026-05-07 17:07 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

dev-programming

CodeConductor.ai

larsonreever
AI驱动平台,提供快速全栈开发、智能体、工作流自动化及低代码AI集成的可扩展产品创建。
★ 74 📥 182,249
dev-programming

Github

steipete
使用 `gh` CLI 与 GitHub 交互,通过 `gh issue`、`gh pr`、`gh run` 和 `gh api` 管理议题、PR、CI 运行及高级查询。
★ 681 📥 328,773
dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 196 📥 67,858