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

Big-O Notation

Algorithms PHP 5.0+ Intermediate
debt(d7/e5/b3/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7) — phpstan won't catch O(n^2); Blackfire profiling at runtime with realistic data is the main signal, otherwise it's silent until production scale.

e5 Effort Remediation debt — work required to fix once spotted

Closest to 'touches multiple files / significant refactor in one component' (e5) — quick_fix suggests swapping in_array for hash lookups (e3-ish for one spot), but real complexity issues often require restructuring data flow across a component, not a one-liner.

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

Closest to 'localised tax' (b3) — a poorly-chosen algorithm burdens the component containing it; it's a local hotspot rather than shaping the whole system, though applies_to spans web/cli/queue.

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

Closest to 'notable trap (documented gotcha)' (t5) — misconception states O(1) doesn't mean instant and large constants can beat small-n linear algorithms; this is the classic gotcha most devs eventually learn but mis-apply early on.

About DEBT scoring →

Also Known As

Big O O-notation Landau notation asymptotic notation

TL;DR

A mathematical notation describing how an algorithm's time or space requirements grow relative to input size, ignoring constants and lower-order terms.

Explanation

Big-O expresses worst-case growth: O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n) linearithmic, O(n^2) quadratic, O(2^n) exponential. The goal is to choose the lowest complexity class for the problem. O(1) operations (hash lookup, array index access) are always fast regardless of input size. O(n^2) operations (nested loops over the same data) become catastrophic at scale — 1000 items takes a million operations.

Diagram

graph TD
    subgraph Complexity_Growth
        O1["O(1) constant"]
        OLOG["O(log n) logarithmic"]
        ON["O(n) linear"]
        ONLOG["O(n log n) linearithmic"]
        ON2["O(n^2) quadratic"]
        O2N["O(2^n) exponential"]
    end
    O1 --> OLOG
    OLOG --> ON
    ON --> ONLOG
    ONLOG --> ON2
    ON2 --> O2N
    style O1 fill:#238636
    style OLOG fill:#238636
    style ON fill:#d29922
    style ONLOG fill:#d29922
    style ON2 fill:#f85149
    style O2N fill:#f85149

Common Misconception

O(1) means instant — it means constant time regardless of n, but the constant could still be large; O(1) with a large constant can be slower than O(n) for small n.

Why It Matters

An O(n^2) algorithm that works fine in development with 100 rows silently becomes unusable in production with 100,000 rows — understanding Big-O prevents this.

Common Mistakes

  • Nested loops over the same collection — almost always O(n^2) or worse; usually fixable with a hash map.
  • in_array() inside a loop — O(n^2) total; use array_flip + isset for O(n).
  • Sorting inside a loop — sort() is O(n log n); sort once before the loop.
  • Not considering space complexity alongside time complexity — an O(n) time algorithm may use O(n^2) memory.

Avoid When

  • Comparing algorithms with identical Big-O complexity but vastly different constant factors — Big-O hides the practical runtime difference between O(n) with coefficient 2 versus coefficient 1000.
  • Analyzing real-time systems or embedded devices where absolute latency bounds matter more than asymptotic growth — a O(n log n) sort that takes 50ms is worse than O(n^2) that takes 5ms for production constraints.
  • Evaluating small, fixed-size inputs where Big-O analysis becomes meaningless — sorting 5 items offers no insight into whether you chose merge sort versus bubble sort.
  • Assessing I/O-bound or memory-constrained operations where wall-clock time is dominated by disk/network access, not CPU cycles — Big-O ignores these system realities entirely.

When To Use

  • Choosing between candidate algorithms for a new feature: compare their Big-O complexity to predict which will handle growth to target scale (e.g., 1M records) without rewrite.
  • Identifying performance bottlenecks in production: if a service degrades nonlinearly with load, Big-O analysis reveals whether the culprit is O(n^2) logic that needs restructuring or acceptable O(n log n) behavior.
  • Designing data structures for a system: decide between a hash table (O(1) lookup) versus a sorted array (O(log n) binary search) based on whether your workload prioritizes read speed or memory density.
  • Code review or technical interview: quickly evaluate whether a proposed solution scales, especially catching nested loops or recursive calls that hide quadratic or exponential cost.

Code Examples

💡 Note
The bad code uses nested foreach loops to search for matching products, creating O(n²) comparisons, while the good code pre-indexes products by ID in a hash table lookup, reducing the search to O(n) total operations.
✗ Vulnerable
// O(n^2) — nested loop over same data:
foreach ($orders as $order) {
    foreach ($products as $product) {
        if ($order->product_id === $product->id) {
            // Found match
        }
    }
}
✓ Fixed
// O(n) — index products by ID first:
$productIndex = [];
foreach ($products as $p) $productIndex[$p->id] = $p;

foreach ($orders as $order) {
    $product = isset($productIndex[$order->product_id]) ? $productIndex[$order->product_id] : null;
}

Added 15 Mar 2026
Edited 26 Aug 2026
Views 208
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
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 1 ping M 1 ping T 0 pings W 1 ping T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 1 ping T 0 pings F 0 pings S 0 pings S 2 pings M 2 pings T 0 pings W 0 pings T 2 pings F 1 ping S
Perplexity 1
Perplexity 1 Amazonbot 1
Scrapy 47 Perplexity 20 Amazonbot 20 Google 9 Ahrefs 9 SEMrush 8 PetalBot 7 ChatGPT 5 Bing 5 Unknown AI 3 Applebot 2 Majestic 1 Sogou 1 Twitter/X 1 Brave Search 1 Baidu 1 Qwen 1
crawler 139 crawler_json 2
🧱 FUNDAMENTALS — new to this? Start with the ground floor.
Algorithm general An algorithm is a step-by-step set of instructions that solves a specific problem or performs a task, like a recipe your code follows to get from input to output.

Every piece of software is algorithms working together. Understanding them helps you write code that actually solves problems efficiently, and lets you recognize when a slow program needs a better approach rather than just faster hardware.

💡 Before writing code, describe your algorithm in plain sentences—if you can't explain the steps clearly, you're not ready to code them.

Ask Codex about Algorithm →
Binary Search algorithms Binary search is a way to find an item in a sorted list by repeatedly cutting the search range in half. Instead of checking every item, you jump to the middle and eliminate half the list each step.

Binary search turns slow linear scans into near-instant lookups, and the halving pattern shows up everywhere — in databases, autocomplete, version control bisects, and countless other algorithms.

💡 Sort first, then halve the range every step — and always move past the middle, never onto it.

Ask Codex about Binary Search →
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Medium
⚡ Quick Fix
Before optimising, identify the complexity class — O(n^2) in a loop over 10,000 items is 100M operations; replacing with a hash lookup makes it O(n)
📦 Applies To
PHP 5.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
Nested loops over the same collection; in_array inside a loop over large dataset (O(n^2)); array_search in hot path
Auto-detectable: ✗ No phpstan blackfire
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: High Context: Function Tests: Update


✓ schema.org compliant