Last active
August 29, 2015 14:07
-
-
Save albertofem/96f3361f9a61c9803cc3 to your computer and use it in GitHub Desktop.
Reflection benchmark
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 | |
define('NUM_TESTS', 10); | |
class Model | |
{ | |
private $property; | |
public function getProperty() | |
{ | |
return $this->property; | |
} | |
public function setProperty($property) | |
{ | |
$this->property = $property; | |
} | |
} | |
function test_accessors() | |
{ | |
echo "Using accessors\n"; | |
$start = microtime(true); | |
$model = new Model; | |
$end = microtime(true); | |
echo "Initializing: " . number_format(1000000 * ($end - $start), 3) . " µsec\n\n"; | |
for($i=0; $i<NUM_TESTS; $i++) { | |
$start = microtime(true); | |
$model->setProperty(mt_rand(0, 21312312321)); | |
$end = microtime(true); | |
echo "Accessors #$i: " . number_format(1000000 * ($end - $start), 3) . " µsec\n"; | |
} | |
echo "\n"; | |
} | |
function test_reflection() | |
{ | |
echo "Using reflection\n"; | |
$start = microtime(true); | |
$model = new Model; | |
$modelReflection = new ReflectionObject($model); | |
$end = microtime(true); | |
echo "Initializing: " . number_format(1000000 * ($end - $start), 3) . " µsec\n\n"; | |
for($i=0; $i<NUM_TESTS; $i++) { | |
$start = microtime(true); | |
$property = $modelReflection->getProperty('property'); | |
$property->setAccessible(true); | |
$property->setValue($model, 'test'); | |
$end = microtime(true); | |
echo "Reflection #$i: " . number_format(1000000 * ($end - $start), 3) . " µsec\n"; | |
} | |
echo "\n"; | |
} | |
test_accessors(); | |
gc_collect_cycles(); | |
test_reflection(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output: