← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

Heaps & Priority Queues

Data Structures PHP 5.3+ Intermediate
debt(d7/e3/b3/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7). The detection_hints indicate automated detection is 'no' and the only listed tool is Blackfire (a profiler), meaning the misuse — using array+sort() instead of a heap — is invisible until performance is measured under load. A linter will not flag it; it requires profiling or attentive code review to spot the O(n log n) vs O(log n) pattern difference.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3). The quick_fix states: replace array+sort() with SplMinHeap or SplMaxHeap. This is a contained refactor — swap out the data structure and update insertion/extraction call sites — but it likely touches a few methods in one component rather than a single-line patch, putting it at e3 rather than e1.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3). The misuse is typically confined to one component (a scheduler, event loop, or pathfinding routine). The rest of the codebase is unaffected; only the code using the priority queue pays the performance penalty. The applies_to scope (web, cli) is broad, but actual heap usage is concentrated, so the structural burden is localised.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5). The misconception field explicitly states: 'A sorted array is a good priority queue' — a documented gotcha that most developers eventually learn. Additionally, the common_mistakes note that SplMaxHeap vs SplMinHeap confusion (getting largest when you wanted smallest) is a real gotcha. These are well-known but non-obvious surprises, fitting t5.

About DEBT scoring →

Also Known As

priority queue min-heap max-heap SplMinHeap

TL;DR

A tree-based structure satisfying the heap property — min-heap: parent ≤ children; max-heap: parent ≥ children — enabling O(1) peek and O(log n) insert/extract for priority queues.

Explanation

A binary heap is a complete binary tree stored in an array. For node at index i: left child at 2i+1, right at 2i+2, parent at (i-1)/2. Heapify maintains the heap property in O(log n). Building a heap from n elements is O(n) — not O(n log n). Priority queue applications: task scheduling, Dijkstra's algorithm, Huffman coding, event simulation. PHP's SplMinHeap and SplMaxHeap implement min and max heaps respectively.

Diagram

flowchart TD
    subgraph Min_Heap
        ROOT2[1 - root always minimum]
        ROOT2 --> L3[3]
        ROOT2 --> R3[2]
        L3 --> LL2[7]
        L3 --> LR2[4]
        R3 --> RL2[5]
    end
    INSERT[insert 2] -->|add at end then bubble up| ROOT2
    EXTRACT[extract min] -->|remove root move last to top sink down| ROOT2
    subgraph Complexity
        INS_C[insert: O of log n]
        EXT_C[extract min: O of log n]
        PEEK[peek min: O of 1]
    end
style ROOT2 fill:#238636,color:#fff
style INS_C fill:#1f6feb,color:#fff

Common Misconception

A sorted array is a good priority queue — sorted array insertion is O(n); heap insertion is O(log n) and peek is O(1).

Why It Matters

Priority queues are used in job schedulers, event loops, and pathfinding — using a sorted array instead of a heap turns O(n log n) algorithms into O(n²).

Common Mistakes

  • Using array + sort() as a priority queue — O(n log n) per insertion vs O(log n) for a heap.
  • Not understanding that a heap is not fully sorted — only the root is guaranteed to be the min/max.
  • Using SplMaxHeap when SplMinHeap is needed — SplMaxHeap returns the largest element, not the smallest.
  • Reinventing a priority queue with array sorting in PHP when SplMinHeap exists.

Code Examples

✗ Vulnerable
// Array as priority queue — O(n log n) per operation:
$queue = [];
foreach ($tasks as $task) {
    $queue[] = $task;
    usort($queue, fn($a, $b) => $a['priority'] <=> $b['priority']); // O(n log n) each!
}
$next = array_shift($queue); // O(n) reindex
✓ Fixed
// SplMinHeap — O(log n) insert, O(1) peek, O(log n) extract:
class TaskHeap extends SplMinHeap {
    protected function compare(mixed $a, mixed $b): int {
        return $b['priority'] <=> $a['priority']; // Lower number = higher priority
    }
}
$heap = new TaskHeap();
foreach ($tasks as $task) $heap->insert($task); // O(log n)
$next = $heap->top();    // O(1) peek
$next = $heap->extract(); // O(log n) extract

Added 15 Mar 2026
Edited 22 Mar 2026
Views 54
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings W 2 pings T 0 pings F 0 pings S 0 pings S 0 pings M 2 pings T 2 pings W 0 pings T 0 pings F 1 ping S 1 ping S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W 1 ping T 0 pings F 0 pings S 1 ping S 1 ping M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Amazonbot 7 Perplexity 6 Ahrefs 5 SEMrush 5 Scrapy 5 Google 4 Unknown AI 3 Claude 2 ChatGPT 2 Majestic 1 Meta AI 1 Bing 1 PetalBot 1
crawler 38 crawler_json 4 pre-tracking 1
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Medium
⚡ Quick Fix
Use PHP's SplMinHeap or SplMaxHeap for priority queues — they maintain heap order automatically with O(log n) insert/extract, much better than sorting an array each time
📦 Applies To
PHP 5.3+ web cli
🔗 Prerequisites
🔍 Detection Hints
Sorting array to get min/max element repeatedly in O(n log n) when heap would do it O(log n); priority queue implemented as sorted array
Auto-detectable: ✗ No blackfire
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: Medium ✗ Manual fix Fix: Medium Context: Class Tests: Update


✓ schema.org compliant