Skip to content

Instantly share code, notes, and snippets.

@alanpich
Created March 11, 2014 21:13
Show Gist options
  • Save alanpich/9495230 to your computer and use it in GitHub Desktop.
Save alanpich/9495230 to your computer and use it in GitHub Desktop.
Benchmarking dependency injection techniques in PHP
Test 1: Setting a public property directly
- 1000000 iterations in 0.49191880226135ms
Test 2: Setting a private property via setter method
- 1000000 iterations in 11.216212034225ms
Test 3: Setting a private property via Reflection
- 1000000 iterations in 11.286839008331ms
Test 4: Setting a protected property via Reflection
- 1000000 iterations in 11.307084083557ms
<?php
class TestClass {
public $myPublicProperty;
protected $myProtectedProperty;
private $myPrivateProperty;
public function setMyPrivateProperty($p){
$this->myPrivateProperty = $p;
}
}
/*
* TEST 1 - Setting a public property directly
*/
echo "Test 1: Setting a public property directly\n";
$k = 0;
$start = microtime(true);
while($k<1000000){
$myClass = new TestClass();
$myClass->myPublicProperty = 'foo';
++$k;
}
$time = microtime(true) - $start;
echo " - $k iterations in {$time}ms\n\n";
/*
* TEST 2 - Setting a private property via a setter
*/
echo "Test 2: Setting a private property via setter method\n";
$k = 0;
$start = microtime(true);
while($k<1000000){
$myClass = new TestClass();
$myClass->setMyPrivateProperty('foo');
++$k;
}
$time = microtime(true) - $start;
echo " - $k iterations in {$time}ms\n\n";
/*
* TEST 3 - Setting a public property directly
*/
echo "Test 3: Setting a private property via Reflection\n";
$refl = new ReflectionClass('TestClass');
$privateProperty = $refl->getProperty('myPrivateProperty');
$privateProperty->setAccessible(true);
$k = 0;
$start = microtime(true);
while($k<1000000){
$myClass = new TestClass();
$privateProperty->setValue($myClass,'foo');
++$k;
}
$time = microtime(true) - $start;
echo " - $k iterations in {$time}ms\n\n";
/*
* TEST 4 - Just out of interest, what about protected properties?
*/
echo "Test 4: Setting a protected property via Reflection\n";
$refl = new ReflectionClass('TestClass');
$protectedProperty = $refl->getProperty('myProtectedProperty');
$protectedProperty->setAccessible(true);
$k = 0;
$start = microtime(true);
while($k<1000000){
$myClass = new TestClass();
$protectedProperty->setValue($myClass,'foo');
++$k;
}
$time = microtime(true) - $start;
echo " - $k iterations in {$time}ms\n\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment