Today I decided to find out which is faster, numerically indexed arrays, or name/value (hash) type arrays.
The result is shocking.
Code: Select all
Average for numeric lookup: 0.00121617 msec
Average for hash-based lookup: 0.00000271 msec
Hash-based vs numeric ratio = 1 : 449.59
Average for numeric lookup: 0.00126696 msec
Average for hash-based lookup: 0.00000232 msec
Hash-based vs numeric ratio = 1 : 545.14
Average for numeric lookup: 0.00126004 msec
Average for hash-based lookup: 0.00000213 msec
Hash-based vs numeric ratio = 1 : 591.56
Average for numeric lookup: 0.00153804 msec
Average for hash-based lookup: 0.00000202 msec
Hash-based vs numeric ratio = 1 : 761.45
Average for numeric lookup: 0.00145197 msec
Average for hash-based lookup: 0.00000234 msec
Hash-based vs numeric ratio = 1 : 620.23
Average for numeric lookup: 0.00121593 msec
Average for hash-based lookup: 0.00000214 msec
Hash-based vs numeric ratio = 1 : 567.11
Average for numeric lookup: 0.00118804 msec
Average for hash-based lookup: 0.00000201 msec
Hash-based vs numeric ratio = 1 : 590.47
Average for numeric lookup: 0.00122190 msec
Average for hash-based lookup: 0.00000198 msec
Hash-based vs numeric ratio = 1 : 616.43
Average for numeric lookup: 0.00119185 msec
Average for hash-based lookup: 0.00000214 msec
Hash-based vs numeric ratio = 1 : 558.24
Average for numeric lookup: 0.00118995 msec
Average for hash-based lookup: 0.00000198 msec
Hash-based vs numeric ratio = 1 : 600.10Run the benchmark and see for yourself:
Code: Select all
<?php
header('Content-Type: text/plain');
$n = array();
$n[] = 'one';
$n[] = 'two';
$n[] = 'three';
$n[] = 'four';
$n[] = 'five';
$n[] = 'six';
$n[] = 'seven';
$n[] = 'eight';
$n[] = 'nine';
$n[] = 'ten';
$h = array(
"1" => "one",
"2" => "two",
"3" => "three",
"4" => "four",
"5" => "five",
"6" => "six",
"7" => "seven",
"8" => "eight",
"9" => "nine",
"10" => "ten"
);
define('REPEAT', 1000);
for ($tests=0; $tests<10; $tests++) {
// --- Benchmark numeric lookup:
$s = microtime(true);
for ($i=0; $i<REPEAT; $i++) {
$test = $n[0];
$test = $n[1];
$test = $n[2];
$test = $n[3];
$test = $n[4];
$test = $n[5];
$test = $n[6];
$test = $n[7];
$test = $n[8];
$test = $n[9];
}
$e = microtime(true);
$num_lag = 1000*(($e-$s)/REPEAT);
echo "Average for numeric lookup: " . number_format($num_lag,8) . " msec\n";
// --- Benchmark hash-based lookup:
$s = microtime(true);
for ($i=0; $i<REPEAT; $i++) {
$test = $h['1'];
$test = $h['2'];
$test = $h['3'];
$test = $h['4'];
$test = $h['5'];
$test = $h['6'];
$test = $h['7'];
$test = $h['8'];
$test = $h['9'];
$test = $h['10'];
}
$e = microtime(true);
$hash_lag = ($e-$s)/REPEAT;
echo "Average for hash-based lookup: " . number_format($hash_lag,8) . " msec\n";
echo "Hash-based vs numeric ratio = 1 : " . number_format($num_lag/$hash_lag,2) . "\n\n";
}
?>