Skip to content

Instantly share code, notes, and snippets.

Created July 22, 2011 14:31
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 anonymous/1099566 to your computer and use it in GitHub Desktop.
Save anonymous/1099566 to your computer and use it in GitHub Desktop.
benchmark demonstrating static method-calls being slower than instance method-calls in PHP
<?php
/*
This benchmarks demonstrates that static method-calls are slower than instance method-calls.
Typical results:
Static method-calls: 157.247 msec
Instance method-calls: 120.566 msec
Static method-call overhead: 30%
*/
header('Content-type: text/plain');
// benchmark static vs instance method-calls
define('NUM_RUNS', 100000);
class A
{
public static function getValue()
{
return 'VALUE';
}
}
class B
{
public function getValue()
{
return 'VALUE';
}
}
// benchmark static method-calls:
$a_value = '';
$start = microtime(true);
for ($i=0; $i<NUM_RUNS; $i++)
{
$a_value .= A::getValue();
}
$end = microtime(true);
$a_time = 1000 * ($end-$start);
echo 'Static method-calls: ' . number_format($a_time, 3) . ' msec' . "\n";
// benchmark instance method-calls:
$b = new B;
$b_value = '';
$start = microtime(true);
for ($i=0; $i<NUM_RUNS; $i++)
{
$b_value .= $b->getValue();
}
$end = microtime(true);
$b_time = 1000 * ($end-$start);
echo 'Instance method-calls: ' . number_format(1000 * ($end-$start), 3) . ' msec' . "\n";
// assert correctness:
if ($a_value !== $b_value)
die('Inconsistent test-result!');
// compare results:
echo 'Static method-call overhead: ' . number_format(100 * ($a_time / $b_time) - 100) . '%' . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment