Skip to content

Instantly share code, notes, and snippets.

@sblomberg
Last active June 6, 2016 19:33
Show Gist options
  • Save sblomberg/fe4cf701da50a8b323aede54d24686d5 to your computer and use it in GitHub Desktop.
Save sblomberg/fe4cf701da50a8b323aede54d24686d5 to your computer and use it in GitHub Desktop.
PHP Constructor vs Static Init performance test
<pre>
<?php
ini_set( 'display_errors', 'On' );
error_reporting( E_ALL );
function test_function() {
$test = rand();
return $test;
}
class StaticInit {
public static function init() {
$test = rand();
return $test;
}
}
class Constructor {
public function __construct() {
$test = rand();
return $test;
}
}
function do_function( $times ) {
for ( $i = 0; $i < $times; $i++ ) {
test_function();
}
}
function do_static( $times ) {
for ( $i = 0; $i < $times; $i++ ) {
StaticInit::init();
}
}
function do_constructor( $times ) {
for ( $i = 0; $i < $times; $i++ ) {
new Constructor();
}
}
$times_to_execute = 100000;
echo "Times executing test: $times_to_execute\n\n";
$startTime = microtime(true);
do_function( $times_to_execute );
$functionDuration = number_format(( microtime(true) - $startTime), 6);
echo "Time with function-only: $functionDuration Seconds\n";
$startTime = microtime(true);
do_static( $times_to_execute );
$staticDuration = number_format(( microtime(true) - $startTime), 6);
echo "Time with static: $staticDuration Seconds\n";
$startTime = microtime(true);
do_constructor( $times_to_execute );
$constructorDuration = number_format(( microtime(true) - $startTime), 6);
echo "Time with constructor: $constructorDuration Seconds\n";
$faster = number_format( $staticDuration / $constructorDuration, 3 ) * 100;
echo "\nConstructor method is $faster% the speed of the Static method"
?>
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment