Бортовой журнал Ктулху

Hash Maps vs Loops — Fatality in PHP Performance

Many PHP developers use nested loops for data lookups or joins. But in some cases, a simple hash map (associative array) can make your code several times faster.

Let’s compare them with two short benchmarks (10 000 records each).

 

landscape comp

 

1). Joining Users and Orders by Email Naive nested loops:

foreach ($orders as $o)
foreach ($users as $u)
if ($u['email'] === $o['email']) { $found++; break; }

~480 ms on 10 000×10 000 items

Using a hash map:

$map = array_column($users, 'id', 'email');
foreach ($orders as $o)
if (isset($map[$o['email']]))
$found++;

~80 ms — about 6× faster

Complexity drops from O(n²) to O(n).

2). When a Simple Loop Is Still Better Task:

count all orders with amount > 1000.

Plain loop:

$count = 0;
foreach ($orders as $o)
if ($o['amount'] > 1000)
$count++;

~1.8 ms

Unnecessary hash:

$tmp = [];
foreach ($orders as $o)
$tmp[$o['id']] = $o['amount'] > 1000;
$count = count(array_filter($tmp));

~2.4 ms — slower, more memory, no gain.

Use hash maps for lookups. When you need to find something fast — like matching a user by email or checking if an ID exists — a hash map wins. It finds items in constant time O(1), even with thousands of records.

Use loops for simple scans. When you just go through everything once — counting, summing, or filtering — a loop is perfect. It’s simple, clear, and uses less memory.

Bottom line: Don’t over-optimize small loops. But if you ever write a nested loop — stop and ask yourself: “Can this be a hash map instead?"