detect-memory-issues

检测 PHP 代码中的内存问题。查找内存中的大数组、缺失的生成器、内存泄漏、无界数据加载以及低效的数据结构。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "detect-memory-issues":https://skillpi.com/zh/skills/deepskill-2647ed0785d338fba6f07f36aab8df3da612eba1d28cd4a5537a21f906e43af5。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

检测 PHP 代码中的内存问题。查找内存中的大数组、缺失的生成器、内存泄漏、无界数据加载以及低效的数据结构。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: detect-memory-issues
description: Detects memory issues in PHP code. Finds large arrays in memory, missing generators, memory leaks, unbounded data loading, inefficient data structures.

Memory Issue Detection

Analyze PHP code for memory usage problems.

Detection Patterns

1. Large Arrays in Memory

// MEMORY HOG: Loading entire table
$users = $repository->findAll(); // 1M users = OOM
foreach ($users as $user) {
    process($user);
}

// MEMORY HOG: Building large array
$data = [];
foreach ($hugeDataset as $item) {
    $data[] = transform($item); // Array grows unbounded
}

// FIXED: Use generator
function processUsers(Repository $repo): Generator {
    foreach ($repo->iterate() as $user) {
        yield transform($user);
    }
}

2. Missing Generators

// MEMORY HOG: Entire file in memory
$lines = file('large-file.txt'); // 1GB file = OOM
foreach ($lines as $line) {
    process($line);
}

// FIXED: Generator-based reading
function readLines(string $path): Generator {
    $handle = fopen($path, 'r');
    while (($line = fgets($handle)) !== false) {
        yield $line;
    }
    fclose($handle);
}

// MEMORY HOG: Collect then process
function getAllProducts(): array {
    $products = [];
    foreach ($this->fetchBatch() as $batch) {
        $products = array_merge($products, $batch);
    }
    return $products; // Entire dataset
}

3. Unbounded Data Loading

// MEMORY HOG: No LIMIT
$logs = $repository->findBy(['level' => 'error']);
// Could be millions of records

// MEMORY HOG: Pagination loading all
$page = 1;
$allItems = [];
do {
    $items = $api->fetch($page++);
    $allItems = array_merge($allItems, $items);
} while (!empty($items));

// FIXED: Process in batches
$page = 1;
do {
    $items = $api->fetch($page++);
    foreach ($items as $item) {
        yield $item;
    }
} while (!empty($items));

4. Object Graph Loading

// MEMORY HOG: Deep object graph
$department = $repo->find($id);
$employees = $department->getEmployees(); // Loads all
foreach ($employees as $emp) {
    $projects = $emp->getProjects(); // Loads more
    foreach ($projects as $project) {
        $tasks = $project->getTasks(); // Even more
    }
}
// Entire object graph in memory

5. Accumulating the Whole Output in Memory

// MEMORY HOG: peak memory holds the ENTIRE output at once
$output = '';
foreach ($lines as $line) {
    $output .= $line . "\n"; // `.=` reallocs in place — the cost is peak
                             // memory (O(total length)), NOT a copy per pass
}

// NOT a fix for memory: an array of n strings costs MORE than the concatenated
// string (each element carries zval + hashtable overhead). Only use implode()
// when you need the parts anyway.
$parts = [];
foreach ($lines as $line) {
    $parts[] = $line;
}
$output = implode("\n", $parts);

// FIXED: stream it out — peak memory becomes O(1) per line
$handle = fopen('output.txt', 'w');
foreach ($lines as $line) {
    fwrite($handle, $line . "\n");
}
fclose($handle);

Rule: the defect here is retaining the whole payload, not the .= operator. Report it only when the accumulated value is never streamed or flushed, and its size scales with untrusted or unbounded input.

6. Image/Binary Processing

// MEMORY HOG: Entire image in memory
$image = file_get_contents('large-image.jpg');
$processed = processImage($image);
file_put_contents('output.jpg', $processed);

// MEMORY HOG: Multiple image resources
foreach ($images as $path) {
    $img = imagecreatefromjpeg($path);
    $resized = imagescale($img, 100, 100);
    imagejpeg($resized, $outPath);
    // Missing: imagedestroy($img); imagedestroy($resized);
}

7. Cache/Buffer Growth

// MEMORY LEAK: Cache grows unbounded
class Cache {
    private array $data = [];

    public function get(string $key): mixed {
        if (!isset($this->data[$key])) {
            $this->data[$key] = $this->load($key);
            // Never evicted
        }
        return $this->data[$key];
    }
}

// MEMORY LEAK: Event listeners accumulate
$dispatcher->addListener('event', function() {
    // New closure each time
});

8. Doctrine Batch Processing

// MEMORY HOG: Doctrine identity map
foreach ($repository->findAll() as $entity) {
    $entity->process();
    $em->flush(); // Identity map keeps all entities
}

// FIXED: Clear periodically
$batchSize = 100;
$i = 0;
foreach ($repository->iterate() as $entity) {
    $entity->process();
    if (++$i % $batchSize === 0) {
        $em->flush();
        $em->clear(); // Free memory
    }
}
$em->flush();

9. Session/Global Storage

// MEMORY HOG: Large session data
$_SESSION['search_results'] = $hugeArray;

// MEMORY HOG: Static cache
class Service {
    private static array $cache = [];

    public static function process($item) {
        self::$cache[$item->getId()] = $item;
        // Never cleared
    }
}

Grep Patterns

# file() usage
Grep: "file\([^)]+\)" --glob "**/*.php"

# findAll without iterate
Grep: "->findAll\(\)" --glob "**/*.php"

# array_merge in loop
Grep: "foreach.*array_merge" --glob "**/*.php"

# String concatenation in loop
Grep: 'foreach.*\.=' --glob "**/*.php"

# Static array properties
Grep: "private static array" --glob "**/*.php"

Memory Estimation

Operation Memory Usage
1M integers in array ~32 MB
1M strings (avg 50 chars) ~250 MB
1M Doctrine entities ~500 MB - 2 GB
1 GB file via file() ~1 GB + overhead

Severity Classification

Pattern Severity
Unbounded data loading 🔴 Critical
Full table in memory 🔴 Critical
Missing imagedestroy 🟠 Major
Static cache without limit 🟠 Major
String concat in loop 🟡 Minor

Output Format

### Memory Issue: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Estimated Memory:** ~500 MB for 100K records

**Issue:**
[Description of the memory problem]

**Code:**
```php
// Memory-intensive code

Fix:

// Memory-efficient alternative

Memory Reduction: Before: ~500 MB peak After: ~10 MB peak (streaming)



## When This Is Acceptable

- **CLI commands/workers** — Console commands may legitimately use more memory for batch processing
- **Known bounded datasets** — Loading all items when the table is guaranteed small (e.g., countries, currencies)
- **Cached data** — Large arrays that are built once and cached for reuse

### False Positive Indicators
- Code is in a console command or queue worker with explicit memory management
- Collection is loaded from a known-small dataset (< 1000 records by business rule)
- Large array is built for cache warming with explicit garbage collection

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

  • PHP 内存问题检测是开发中的高频刚需,尤其适用于大数据处理、API 服务和批处理任务
  • 提供了完整的检测模式、修复方案、Grep 模式、内存估算和严重性分级,实用价值极高
触发精准90/100

亮点

  • description 明确描述了功能范围,涵盖大型数组、生成器缺失、内存泄漏等关键场景
  • 边界清晰,覆盖多种变体,触发词精准完整
结构规范95/100

亮点

  • 文档结构清晰,包含多个检测模式,每个模式都有问题代码和修复代码对比
  • 提供了 Grep 模式、内存估算表、严重性分类、输出格式和例外说明,frontmatter 完整
执行可靠90/100

亮点

  • 提供了具体的 Grep 命令用于检测问题,给出了内存估算和严重性分级
  • 输出格式规范,作为代码审查辅助工具具有高度可执行性
证据可验 (前四项均值)93/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。