Skip to content

Instantly share code, notes, and snippets.

@mattclegg
Created January 4, 2016 20:05
Show Gist options
  • Save mattclegg/65c9aec0e43618c91b6b to your computer and use it in GitHub Desktop.
Save mattclegg/65c9aec0e43618c91b6b to your computer and use it in GitHub Desktop.
Benchmark: PHP Reverse
<?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