Skip to content

Instantly share code, notes, and snippets.

@Atulin
Created August 15, 2019 00:41
Show Gist options
  • Save Atulin/0890a5ddf35b7b5407a46d96658e6b97 to your computer and use it in GitHub Desktop.
Save Atulin/0890a5ddf35b7b5407a46d96658e6b97 to your computer and use it in GitHub Desktop.

Simple benchmark checking access speeds in arrays defined in different ways. Don't ask why I made it, 'cause I can't find an explanation either ¯\_(ツ)_/¯

I ran it a few times, and I don't even know why I bothered. Access times are negligibly and inconsistently different. And even when they are, it's in the ballpark of tenths of a nanosecond.

<?php
define('DEF', [
'key' => 'value',
'complex' => [
'key' => 'value',
'complex' => [
'key' => 'value'
]
]
]);
const CST = [
'key' => 'value',
'complex' => [
'key' => 'value',
'complex' => [
'key' => 'value'
]
]
];
$arr = [
'key' => 'value',
'complex' => [
'key' => 'value',
'complex' => [
'key' => 'value'
]
]
];
$score = [
'define' => 0,
'constant' => 0,
'array' => 0,
];
for ($i = 0; $i < 100; $i++) {
$ds = microtime(true);
echo DEF['complex']['complex']['key'];
$de = microtime(true);
$cs = microtime(true);
echo CST['complex']['complex']['key'];
$ce = microtime(true);
$as = microtime(true);
echo $arr['complex']['complex']['key'];
$ae = microtime(true);
echo PHP_EOL;
$res = [
'define' => $de-$ds,
'constant' => $ce-$cs,
'array' => $ae-$as,
];
echo json_encode($res, JSON_PRETTY_PRINT);
$maxs = array_keys($res, min($res));
foreach ($maxs as $m) {
$score[$m] += 1;
}
}
echo PHP_EOL.'RESULTS'.PHP_EOL;
echo json_encode($score, JSON_PRETTY_PRINT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment