Created
January 4, 2016 20:05
-
-
Save mattclegg/65c9aec0e43618c91b6b to your computer and use it in GitHub Desktop.
Benchmark: PHP Reverse
This file contains 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 | |
$test_array = array(0,1,2,3,4,5); | |
function getmicrotime() | |
{ | |
list($usec, $sec) = explode(' ',microtime()); | |
return ((float)$usec + (float)$sec); | |
} | |
$time_start = getmicrotime(); | |
for ($i=0; $i<1000000; $i++) | |
{ | |
$j = count($test_array)-1; | |
$result_array = array(); | |
while ($j >= 0) | |
{ | |
$result_array[] = $test_array[$j]; | |
$j--; | |
} | |
} | |
echo 'while() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>'; | |
//var_dump($result_array); | |
$time_start = getmicrotime(); | |
for ($i=0; $i<1000000; $i++) | |
{ | |
$length = count($test_array)-1; | |
$result_array = array(); | |
for ($j=$length; $j>=0; $j--) | |
{ | |
$result_array[] = $test_array[$j]; | |
} | |
} | |
echo 'for() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>'; | |
//var_dump($result_array); | |
$time_start = getmicrotime(); | |
for ($i=0; $i<1000000; $i++) | |
{ | |
$result_array = array(); | |
for ($j=count($test_array)-1; $j>=0; $j--) | |
{ | |
$result_array[] = $test_array[$j]; | |
} | |
} | |
echo 'for() optimized :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>'; | |
//var_dump($result_array); | |
$time_start = getmicrotime(); | |
for ($i=0; $i<1000000; $i++) | |
{ | |
$result_array = array(); | |
foreach($test_array as $j) | |
{ | |
array_unshift($result_array, $test_array[$j]); | |
} | |
} | |
echo 'foreach / array_unshift :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>'; | |
//var_dump($result_array); | |
$time_start = getmicrotime(); | |
for ($i=0; $i<1000000; $i++) | |
{ | |
$result_array = array_reverse($test_array, false); | |
} | |
echo 'array_reverse:: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>'; | |
//var_dump($result_array); | |
$time_start = getmicrotime(); | |
for ($i=0; $i<1000000; $i++) | |
{ | |
$result_array = array_reverse($test_array, true); | |
} | |
echo 'array_reverse (preserve keys):: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>'; | |
//var_dump($result_array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment