Skip to content

Instantly share code, notes, and snippets.

@fernandocarletti
Created October 18, 2013 11:05
Show Gist options
  • Save fernandocarletti/7040004 to your computer and use it in GitHub Desktop.
Save fernandocarletti/7040004 to your computer and use it in GitHub Desktop.
Benchmarking php classes using public methods and getters/setters, as read on https://developers.google.com/speed/articles/optimizing-php
<?php
#################################################
# My machine results (1.000.000 iterations) #
#################################################
# Run | Getters/Setters | Public #
#-----------------------------------------------#
# First | 0.31555795669556 | 0.079293012619019 #
# Second | 0.30993223190308 | 0.072643995285034 #
# Third | 0.32820105552673 | 0.073053121566772 #
#################################################
$iterations = 100000;
class GS
{
protected $property;
public function getProperty()
{
return $this->property;
}
public function setProperty($property)
{
$this->property = $property;
}
}
class P {
public $property;
}
$startTime = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$gs = new GS();
$gs->setProperty('foo');
$gs->getProperty();
}
$totalTime = microtime(true) - $startTime;
echo "Time for getters/setters: {$totalTime} seconds" . PHP_EOL;
$startTime = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$gs = new P();
$gs->property = 'foo';
$gs->property;
}
$totalTime = microtime(true) - $startTime;
echo "Time for public: {$totalTime} seconds" . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment