Created
April 25, 2019 04:21
-
-
Save mikeschinkel/a8112e6b24498eadd54ed051e31e1166 to your computer and use it in GitHub Desktop.
Benchmarks for PHP's Early Returns vs. Do While False
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
<?php | |
define( 'ITERATIONS', 10000000 ); | |
$earlyreturn = time_it( 'early returns (w/value): ', function($condition) { earlyreturn1($condition); }); | |
$dowhilefalse = time_it( 'do while false (w/value):', function($condition) { dowhilefalse1($condition); }); | |
printf( "\nPercent increase (w/value): %.3f", ($dowhilefalse-$earlyreturn)/$dowhilefalse ); | |
printf( "\nPercent difference (w/value): %.3f", 1-($dowhilefalse-$earlyreturn)/$dowhilefalse ); | |
$earlyreturn = time_it( "early returns (no value): ", function($condition) { earlyreturn2($condition); }); | |
$dowhilefalse = time_it( "do while false (no value):", function($condition) { dowhilefalse2($condition); }); | |
printf( "\nPercent increase (no value): %.3f", ($dowhilefalse-$earlyreturn)/$dowhilefalse ); | |
printf( "\nPercent difference (no value): %.3f", 1-($dowhilefalse-$earlyreturn)/$dowhilefalse ); | |
function time_it( $what, $callable ) { | |
$time_start = microtime( true ); | |
$condition = true; | |
for ( $i = 0; $i < ITERATIONS; $i ++ ) { | |
call_user_func( $callable, $condition ); | |
$condition = !$condition; | |
} | |
printf( "\n%s %s %.3f", | |
number_format(ITERATIONS), | |
$what, | |
$delta = microtime( true ) - $time_start | |
); | |
return $delta; | |
} | |
function earlyreturn1($condition) { | |
if ($condition) { | |
return null; | |
} | |
return 1; | |
} | |
function dowhilefalse1($condition) { | |
do { | |
$value = null; | |
if ($condition) { | |
break; | |
} | |
$value = 1; | |
} while (false); | |
return $value; | |
} | |
function earlyreturn2($condition) { | |
if ($condition) { | |
return; | |
} | |
return; | |
} | |
function dowhilefalse2($condition) { | |
do { | |
if ($condition) { | |
break; | |
} | |
} while (false); | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment