Skip to content

Instantly share code, notes, and snippets.

@kemo
Created November 22, 2022 12:46
Show Gist options
  • Save kemo/b180bba7eec7626e02e7755ac5bb96f1 to your computer and use it in GitHub Desktop.
Save kemo/b180bba7eec7626e02e7755ac5bb96f1 to your computer and use it in GitHub Desktop.
php magic __call benchmark
<?php
class MagicMethodFixture {
/**
* @var array
*/
protected $configurations;
public function __construct() {
$this->configurations = array(
'foo' => 'bar',
'Bar' => 'baz'
);
}
/**
* @param string $configurationKey
* @return mixed
*/
public function get($configurationKey) {
return $this->configurations[$configurationKey];
}
/**
* @param string $methodName
* @param array $arguments
* @return mixed
*/
public function __call($methodName, array $arguments) {
if ($methodName === 'getVar')
return $this->get($arguments[0]);
trigger_error('Call to undefined method ' . get_class($this) . '::' . $methodName, E_USER_ERROR);
}
}
$iterations = 1000000;
$fixture = new MagicMethodFixture();
echo '<h2>magic __call:</h2>';
$start = microtime(TRUE);
for ($i = 0; $i < $iterations; $i ++) {
$fixture->getVar('foo');
$fixture->getVar('Bar');
}
$end = microtime(TRUE);
echo '<p>' . ($end - $start) . ' seconds</p>';
echo '<h2>real implementation:</h2>';
$start = microtime(TRUE);
for ($i = 0; $i < $iterations; $i ++) {
$fixture->get('foo');
$fixture->get('Bar');
}
$end = microtime(TRUE);
echo '<p>' . ($end - $start) . ' seconds</p>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment