-
-
Save asika32764/9707fc2afe67d4733cc3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* Benchmark: Reflection Performance | |
* | |
* Conclusion: there is no performance-gain from caching reflection-objects. | |
*/ | |
define('NUM_TESTS', 10); | |
header('Content-type: text/plain'); | |
$func = function($a, $b, $c) { | |
// ... | |
}; | |
class Foo | |
{ | |
public $a; | |
protected $b; | |
private $c; | |
public function foo($a,$b,$c) {} | |
protected function bar($a,$b,$c) {} | |
private function baz($a,$b,$c) {} | |
} | |
for ($i=0; $i<NUM_TESTS; $i++) { | |
$start = microtime(true); | |
$ref = new ReflectionClass($func); | |
$end = microtime(true); | |
echo "ReflectionClass # $i: " . number_format(1000000*($end-$start), 3) . " µsec\n"; | |
} | |
for ($i=0; $i<NUM_TESTS; $i++) { | |
$start = microtime(true); | |
$ref = new ReflectionFunction($func); | |
$end = microtime(true); | |
echo "ReflectionFunction # $i: " . number_format(1000000*($end-$start), 3) . " µsec\n"; | |
} | |
class Cache | |
{ | |
private $cache = array(); | |
public function getReflection($class) | |
{ | |
if (!isset($this->cache[$class])) { | |
$this->cache[$class] = new ReflectionClass($class); | |
} | |
return $this->cache[$class]; | |
} | |
} | |
$cache = new Cache; | |
for ($i=0; $i<NUM_TESTS; $i++) { | |
$start = microtime(true); | |
$ref = $cache->getReflection('Foo'); | |
$end = microtime(true); | |
echo "Cached ReflectionClass # $i: " . number_format(1000000*($end-$start), 3) . " µsec\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment