<?php
interface I {}
class A implements I{}
$results = [];
[$key, $value] = compute('instanceof [object]', function($instance) {
$instance instanceof I;
});
$results[$key] = $value;
[$key, $value] = compute('class_implements [object]', function($instance) {
in_array(I::class, class_implements(A::class));
});
$results[$key] = $value;
[$key, $value] = compute('is_a [object]', function($instance) {
is_a($instance, I::class);
});
$results[$key] = $value;
[$key, $value] = compute('is_a [class]', function($instance) {
is_a(A::class, I::class, true);
});
$results[$key] = $value;
[$key, $value] = compute('reflection [class]', function($instance) {
( new ReflectionClass(A::class))->implementsInterface(I::class);
});
$results[$key] = $value;
function compute($name, $callback) {
$instance = new A;
$start = microtime(true);
for($i = 1e5; $i; $i--) {
$callback($instance);
}
$elapsedMs = (microtime(true) - $start)*1000;
return [$name, $elapsedMs];
}
asort($results);
$best = min($results);
$results = array_map(function($result) use($best) {
return [
$result,
$result / $best,
];
}, $results);
$performance = 0;
foreach($results as $name => $result) {
[$elapsedMs, $performance] = $result;
$extraTimeInPercent = ($performance - 1) * 100;
echo sprintf(
'%25s took %6.2f ms | +%3.0f%% | %s',
$name,
$elapsedMs,
$extraTimeInPercent,
str_pad('', ($performance * 10), '.')
) . PHP_EOL;
}
preferences:
34.63 ms | 413 KiB | 5 Q