Skip to content

Instantly share code, notes, and snippets.

@castroalves
Last active September 24, 2018 13:15
Show Gist options
  • Save castroalves/5535a5885f1dfbdc64cb79dd332277e1 to your computer and use it in GitHub Desktop.
Save castroalves/5535a5885f1dfbdc64cb79dd332277e1 to your computer and use it in GitHub Desktop.
Performance Test: Array to CSV using For vs Implode
<?php
$arr_numbers = range(1,10000);
$total = count($arr_numbers);
$time_for = microtime(true);
$csv_for = '';
for($i = 0; $i < $total; $i++) {
if( $i == ($total - 1) ) {
$csv_for .= strval( $arr_numbers[$i] );
} else {
$csv_for .= $arr_numbers[$i] . ',';
}
}
$time_for = microtime(true) - $time_for;
$time_implode = microtime(true);
$csv_implode = implode(',', $arr_numbers);
$time_implode = microtime(true) - $time_implode;
echo '<h1>Results</h1>';
echo '<h2>Array to CSV using for()</h2>';
echo '<p>' . $csv_for . '</p>';
echo 'Time For: ' . $time_for . ' seconds<br />';
echo '<h2>Array to CSV using implode()</h2>';
echo '<p>' . $csv_implode . '</p>';
echo 'Time Implode: ' . $time_implode . ' seconds<br /><br />';
if( $time_for < $time_implode ) {
echo 'For() is ' . round( $time_for / $time_implode, 2 ) . 'x faster than implode().';
} else {
echo 'Implode() is ' . round( $time_for / $time_implode, 2 ) . 'x faster than for().';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment