Skip to content

Instantly share code, notes, and snippets.

@georgiana-gligor
Created January 9, 2017 15:35
Show Gist options
  • Save georgiana-gligor/78bf61c32990aeb645c21ad1c06666ec to your computer and use it in GitHub Desktop.
Save georgiana-gligor/78bf61c32990aeb645c21ad1c06666ec to your computer and use it in GitHub Desktop.
Performance of null checking
<?php
define('DEFAULT_ITERATIONS', 1000000);
$myNull = null;
$options = getopt('n:');
$iterations = isset($options['n']) ? intval($options['n']) : DEFAULT_ITERATIONS;
logLine('iterations = ' . $iterations);
logLine('>>> Checking `is_null`');
$startTime = lap();
for ($i = 0; $i < $iterations; $i++) {
if (is_null($myNull)) {
continue;
}
}
$endTime = lap();
logDuration($startTime, $endTime);
logLine('>>> Checking `null !== `');
$startTime = lap();
for ($i = 0; $i < $iterations; $i++) {
if (null !== $myNull) {
continue;
}
}
$endTime = lap();
logDuration($startTime, $endTime);
function lap() {
return microtime(true);
}
function logDuration($start, $end) {
$duration = $end - $start;
$message = sprintf('Duration: %f', $duration);
logLine($message);
}
function logLine($message) {
echo $message . PHP_EOL;
}
iterations = 5
>>> Checking `is_null`
Duration: 0.000007
>>> Checking `null !== `
Duration: 0.000004
iterations = 5000000
>>> Checking `is_null`
Duration: 0.089797
>>> Checking `null !== `
Duration: 0.085138
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment