Skip to content

Instantly share code, notes, and snippets.

@felixgirault
Created August 13, 2013 15:55
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 felixgirault/6222639 to your computer and use it in GitHub Desktop.
Save felixgirault/6222639 to your computer and use it in GitHub Desktop.
A benchmark for different ways of using echo in PHP.
<?php
define( 'ECHO_COUNT', 10000 );
define( 'EXECUTION_COUNT', 100 );
function coma( ) {
for ( $i = 0; $i < ECHO_COUNT; $i++ ) {
echo 'a ', $i, ' b ', $i, ' c';
}
}
function dot( ) {
for ( $i = 0; $i < ECHO_COUNT; $i++ ) {
echo 'a ' . $i . ' b ' . $i . ' c';
}
}
function interpolation( ) {
for ( $i = 0; $i < ECHO_COUNT; $i++ ) {
echo "a $i b $i c";
}
}
$results = array(
'coma' => 0,
'dot' => 0,
'interpolation' => 0
);
foreach ( $results as $function => $meanTime ) {
$time = microtime( true );
ob_start( );
for ( $i = 0; $i < EXECUTION_COUNT; $i++ ) {
$function( );
}
ob_end_clean( );
$results[ $function ] = ( microtime( true ) - $time ) / EXECUTION_COUNT;
}
?>
<table>
<thead>
<tr>
<th>Method</th>
<th>Mean time for <?php echo EXECUTION_COUNT; ?> x <?php echo ECHO_COUNT; ?> echoes</th>
</tr>
</thead>
<tbody>
<?php foreach ( $results as $function => $meanTime ): ?>
<tr>
<td><?php echo $function; ?></td>
<td><?php echo $meanTime; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment