3v4l.org

run code in 300+ PHP versions simultaneously
<?php const N = 100_000; const TYPE = 0; function simple_alloc($id, $delete = false, $type = TYPE) { static $ids = []; if (is_int($id)) { $key = $id; } else { $key = array_search($id, $ids[$type] ?? [], true); } if ($delete) { if ($key !== false) { unset($ids[$type][$key]); } return $key; } if ($key === false) { $key = count($ids[$type] ?? []); $ids[$type][$key] = $id; } return $key; } function freelist_alloc($id, $delete = false, $type = TYPE) { static $ids = []; static $freelist = []; $freelist[$type] ??= []; $ids[$type] ??= []; if (is_int($id)) { if ($delete) $freelist[$type][] = $id; return $id; } $match = null; foreach ($ids[$type] as $i => $arr) { if (in_array($i, $freelist[$type], true)) continue; if ($arr === $id) { $match = $i; if ($delete) $freelist[$type][] = $i; break; } } if ($match === null) { $nextId = array_pop($freelist[$type]); if ($nextId === null) { $nextId = count($ids[$type]); $ids[$type][] = $id; } else { $ids[$type][$nextId] = $id; } return $nextId; } return $match; } $t1 = microtime(true); $live1 = []; for ($i = 0; $i < N; $i++) { if ($live1 && mt_rand(0, 1)) { $k = array_rand($live1); simple_alloc($live1[$k], true); unset($live1[$k]); } else { $obj = 'obj-' . $i . '-' . mt_rand(); $id = simple_alloc($obj); $live1[] = $id; } } $dt_simple = microtime(true) - $t1; $t2 = microtime(true); $live2 = []; for ($i = 0; $i < N; $i++) { if ($live2 && mt_rand(0, 1)) { $k = array_rand($live2); freelist_alloc($live2[$k], true); unset($live2[$k]); } else { $obj = 'obj-' . $i . '-' . mt_rand(); $id = freelist_alloc($obj); $live2[] = $id; } } $dt_freelist = microtime(true) - $t2; // --- Results --- echo "Random Allocation/Free Benchmark (N = " . number_format(N) . ")\n"; echo "Simple allocator: " . number_format($dt_simple, 4) . " sec\n"; echo "Freelist allocator: " . number_format($dt_freelist, 4) . " sec\n"; if ($dt_freelist > 0) { echo "Simple is " . number_format($dt_freelist / $dt_simple, 2) . "x faster\n"; } else { echo "\n"; }

preferences:
23.04 ms | 410 KiB | 5 Q