Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.