Skip to content

Instantly share code, notes, and snippets.

@omnicolor
Created March 15, 2012 18:36
Show Gist options
  • Save omnicolor/2045910 to your computer and use it in GitHub Desktop.
Save omnicolor/2045910 to your computer and use it in GitHub Desktop.
<?php
define('RUN_ITERATIONS', 100000);
function avg($array) {
return array_sum($array) / count($array);
}
function ifseta($arr, $k, $default = null) {
return isset($arr[$k]) ? $arr[$k] : $default;
}
$array = range(0, 1000);
$issetTimes = array();
$ifsetaWithDefaultTimes = array();
$ifsetaTimes = array();
$ifsetaNoFuncTimes = array();
$j = 100;
while ($j) {
$i = RUN_ITERATIONS;
$time = microtime(true);
while ($i) {
if (isset($array[rand(0, 2000)])) {
$i--;
} else {
$i --;
}
}
$issetTimes[] = microtime(true) - $time;
$i = RUN_ITERATIONS;
$time = microtime(true);
while ($i) {
if (ifseta($array, rand(0, 2000))) {
$i--;
} else {
$i--;
}
}
$ifsetaTimes[] = microtime(true) - $time;
$i = RUN_ITERATIONS;
$time = microtime(true);
while ($i) {
if (ifseta($array, rand(0, 2000), 5)) {
$i--;
} else {
$i--;
}
}
$ifsetaWithDefaultTimes[] = microtime(true) - $time;
$i = RUN_ITERATIONS;
$time = microtime(true);
while ($i) {
$key = rand(0, 2000);
if (isset($array[$key]) ? $array[$key] : 10) {
$i--;
} else {
$i--;
}
}
$ifsetaNoFuncTimes[] = microtime(true) - $time;
if (0 == $j % 10) {
echo '.';
}
$j--;
}
echo PHP_EOL,
'Isset: ', avg($issetTimes), PHP_EOL,
'Ifseta: ', avg($ifsetaTimes), PHP_EOL,
'ifseta(default): ', avg($ifsetaWithDefaultTimes), PHP_EOL,
'ifseta(native): ', avg($ifsetaNoFuncTimes), PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment