Last active
September 24, 2018 13:15
-
-
Save castroalves/5535a5885f1dfbdc64cb79dd332277e1 to your computer and use it in GitHub Desktop.
Performance Test: Array to CSV using For vs Implode
This file contains hidden or 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 | |
$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