detect-unnecessary-loops

检测 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-unnecessary-loops":https://skillpi.com/zh/skills/deepskill-f77f85cd062c30493e23cfe6dfeeb7bb119cd27c376433b4ad69c25a9db8af64。安装前核对上游来源和版本: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-unnecessary-loops
description: Detects unnecessary loop patterns in PHP code. Finds nested loop inefficiency, redundant iterations, in-loop operations that could be batched, loop invariant code.

Unnecessary Loop Detection

Analyze PHP code for inefficient loop patterns.

Detection Patterns

1. Nested Loop Inefficiency

// O(n*m): Nested search
foreach ($users as $user) {
    foreach ($orders as $order) {
        if ($order->getUserId() === $user->getId()) {
            // Found order for user
        }
    }
}

// O(n): Use indexed lookup
$ordersByUser = [];
foreach ($orders as $order) {
    $ordersByUser[$order->getUserId()][] = $order;
}
foreach ($users as $user) {
    $userOrders = $ordersByUser[$user->getId()] ?? [];
}

2. Redundant Iterations

// REDUNDANT: Multiple passes
$filtered = [];
foreach ($items as $item) {
    if ($item->isActive()) {
        $filtered[] = $item;
    }
}
$transformed = [];
foreach ($filtered as $item) {
    $transformed[] = $item->toArray();
}
$sorted = usort($transformed, fn($a, $b) => $a['name'] <=> $b['name']);

// BETTER: Single pass + built-in sort
$result = [];
foreach ($items as $item) {
    if ($item->isActive()) {
        $result[] = $item->toArray();
    }
}
usort($result, fn($a, $b) => $a['name'] <=> $b['name']);

3. In-Loop Operations That Could Be Batched

// SLOW: Individual inserts
foreach ($users as $user) {
    $this->repository->save($user);
    $this->em->flush(); // Flush each iteration
}

// FAST: Batch insert
foreach ($users as $user) {
    $this->em->persist($user);
}
$this->em->flush(); // Single flush

// SLOW: Individual API calls
foreach ($items as $item) {
    $this->api->update($item); // HTTP call per item
}

// FAST: Batch API call
$this->api->updateBatch($items);

4. Loop Invariant Code

// INEFFICIENT: Repeated computation
foreach ($items as $item) {
    $config = $this->loadConfig(); // Same result each iteration
    $now = new DateTime(); // Same time each iteration
    $taxRate = $this->getTaxRate($country); // Constant
    process($item, $config, $now, $taxRate);
}

// FIXED: Hoist invariants
$config = $this->loadConfig();
$now = new DateTime();
$taxRate = $this->getTaxRate($country);
foreach ($items as $item) {
    process($item, $config, $now, $taxRate);
}

5. Array Functions vs Loops

// VERBOSE: Manual filter
$active = [];
foreach ($users as $user) {
    if ($user->isActive()) {
        $active[] = $user;
    }
}

// CLEANER: array_filter
$active = array_filter($users, fn($u) => $u->isActive());

// VERBOSE: Manual map
$names = [];
foreach ($users as $user) {
    $names[] = $user->getName();
}

// CLEANER: array_map
$names = array_map(fn($u) => $u->getName(), $users);

// VERBOSE: Manual reduce
$total = 0;
foreach ($orders as $order) {
    $total += $order->getAmount();
}

// CLEANER: array_reduce
$total = array_reduce($orders, fn($sum, $o) => $sum + $o->getAmount(), 0);

6. Early Exit Missing

// INEFFICIENT: Continues after finding
foreach ($users as $user) {
    if ($user->getId() === $targetId) {
        $found = $user;
    }
}

// EFFICIENT: Break when found
foreach ($users as $user) {
    if ($user->getId() === $targetId) {
        $found = $user;
        break;
    }
}

// BETTER: Use array_filter/first or collection method
$found = $collection->first(fn($u) => $u->getId() === $targetId);

7. Counting in Loop

// MINOR: strlen() re-evaluated each iteration
for ($i = 0; $i < strlen($string); $i++) {
    // strlen() is O(1) in PHP (the length is stored), so this is n cheap calls,
    // NOT a change of complexity class. Worth hoisting, but it is a Minor finding.
}

// FASTER: hoist the call
$len = strlen($string);
for ($i = 0; $i < $len; $i++) {
    // ...
}

// MAJOR: a genuinely expensive call in the condition
for ($i = 0; $i < $repository->countAll(); $i++) {
    // n database round trips — this one really is a Major finding
}

// SLOW: count() in loop
for ($i = 0; $i < count($array); $i++) {
    // count called each iteration
}

8. Unnecessary array_merge

// SLOW: array_merge in loop creates new array each time
$result = [];
foreach ($batches as $batch) {
    $result = array_merge($result, $batch);
}

// FAST: Spread operator
$result = array_merge(...$batches);

// FAST: Direct append
$result = [];
foreach ($batches as $batch) {
    foreach ($batch as $item) {
        $result[] = $item;
    }
}

Grep Patterns

# Nested foreach
Grep: "foreach.*foreach" --glob "**/*.php"

# flush() in loop
Grep: "foreach.*->flush\(\)" --glob "**/*.php"

# strlen/count in loop condition
Grep: "for\s*\([^;]+;\s*\$\w+\s*<\s*(strlen|count)\(" --glob "**/*.php"

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

Complexity Comparison

Pattern Before After
Nested loop search O(n*m) O(n+m) with index
Multiple passes O(3n) O(n) single pass
In-loop flush n DB round trips 1 round trip
Query/count in condition n DB round trips 1 round trip
strlen/count in condition n cheap O(1) calls 1 call (Minor — same complexity class)

Severity Classification

Pattern Severity
Nested loop O(n²) 🔴 Critical
Individual DB operations in loop 🔴 Critical
Loop invariant code 🟠 Major
Multiple array passes 🟠 Major
strlen in condition 🟡 Minor
Verbose vs array_* 🟢 Suggestion

Output Format

### Unnecessary Loop: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Current Complexity:** O(n²)
**Optimized Complexity:** O(n)

**Issue:**
[Description of the inefficient pattern]

**Code:**
```php
// Inefficient loop

Optimization:

// Optimized version

Improvement: For 1000 items: 1,000,000 ops → 2,000 ops

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

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

场景价值95/100

亮点

  • PHP性能优化是开发者日常核心痛点,该Skill提供具体检测模式、复杂度对比和优化方案,直接提升代码质量
触发精准90/100

亮点

  • 触发词精准完整,覆盖多种变体,边界清晰
结构规范95/100

亮点

  • Phase/步骤清晰,有出口条件,含端到端示例,frontmatter完整,单文件≤500行
执行可靠90/100

亮点

  • 工具来源明确,参数正确,覆盖主要异常,不可逆操作有确认机制
证据可验 (前四项均值)93/100

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

正文静态检测

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

正文未命中当前规则。

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

权限与使用前检查

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

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

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

安全评级与访问范围

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

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