Skip to content

Instantly share code, notes, and snippets.

@albertofem
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albertofem/96f3361f9a61c9803cc3 to your computer and use it in GitHub Desktop.
Save albertofem/96f3361f9a61c9803cc3 to your computer and use it in GitHub Desktop.
Reflection benchmark
<?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();
@albertofem
Copy link
Author

Sample output:

Using accessors
Initializing: 12.159 µsec

Accessors #0: 20.981 µsec
Accessors #1: 2.146 µsec
Accessors #2: 0.954 µsec
Accessors #3: 0.000 µsec
Accessors #4: 1.192 µsec
Accessors #5: 0.954 µsec
Accessors #6: 0.000 µsec
Accessors #7: 0.000 µsec
Accessors #8: 0.000 µsec
Accessors #9: 1.192 µsec

Using reflection
Initializing: 10.014 µsec

Reflection #0: 11.206 µsec
Reflection #1: 5.007 µsec
Reflection #2: 1.907 µsec
Reflection #3: 1.907 µsec
Reflection #4: 0.954 µsec
Reflection #5: 1.192 µsec
Reflection #6: 1.192 µsec
Reflection #7: 1.192 µsec
Reflection #8: 2.146 µsec
Reflection #9: 0.954 µsec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment