<?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";
}
- Output for git.master_jit
- Random Allocation/Free Benchmark (N = 100,000)
Simple allocator: 0.0318 sec
Freelist allocator: 1.7045 sec
Simple is 53.64x faster
- Output for git.master
- Random Allocation/Free Benchmark (N = 100,000)
Simple allocator: 0.0188 sec
Freelist allocator: 1.0756 sec
Simple is 57.34x faster
This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.
Active branches
Archived branches
Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page
preferences:
26.63 ms | 406 KiB | 5 Q