Last active
June 6, 2016 19:33
-
-
Save sblomberg/fe4cf701da50a8b323aede54d24686d5 to your computer and use it in GitHub Desktop.
PHP Constructor vs Static Init performance test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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