Skip to content

Instantly share code, notes, and snippets.

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 mikeschinkel/a8112e6b24498eadd54ed051e31e1166 to your computer and use it in GitHub Desktop.
Save mikeschinkel/a8112e6b24498eadd54ed051e31e1166 to your computer and use it in GitHub Desktop.
Benchmarks for PHP's Early Returns vs. Do While False
<?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