Last active
April 10, 2016 15:46
-
-
Save BenMorel/7acd6f2c0ae11d3cce7208a330cff372 to your computer and use it in GitHub Desktop.
Benchmarks the impact of type-hinting on PHP variadic functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$variadics = 1000; // number of objects passed to each variadic function | |
$iterations = 1000; // number of calls of each function | |
class Foo { | |
} | |
function withoutTypeHinting(...$foos) { | |
} | |
function withTypeHinting(Foo ...$foos) { | |
} | |
function withManualTypeCheck(...$foos) { | |
foreach ($foos as $foo) { | |
if (! $foo instanceof Foo) { | |
throw new TypeError('Expected instance of Foo'); | |
} | |
} | |
} | |
$foos = []; | |
for ($i = 0; $i < $variadics; $i++) { | |
$foos[] = new Foo; | |
} | |
function benchmark($function) { | |
global $iterations, $foos; | |
$t = microtime(true); | |
for ($i = 0; $i < $iterations; $i++) { | |
$function(...$foos); | |
} | |
return microtime(true) - $t; | |
} | |
$withoutTypeHinting = benchmark('withoutTypeHinting'); | |
$withTypeHinting = benchmark('withTypeHinting'); | |
$withManualTypeCheck = benchmark('withManualTypeCheck'); | |
printf("Without type-hinting: %.6f s\n", $withoutTypeHinting); | |
printf("With type-hinting: %.6f s\n", $withTypeHinting); | |
printf("With manual type check: %.6f s\n", $withManualTypeCheck); | |
printf("Type-hinting overhead: %.1f %%\n", (($withTypeHinting / $withoutTypeHinting) - 1) * 100); | |
printf("Type-hinting improvement over manual check: %.1f %%\n", (($withManualTypeCheck / $withTypeHinting) - 1) * 100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment