Steven Vachon

Benchmark: PHP Reverse Array while vs. for vs. foreach

0 comments

When looping through an array in reverse and wondering which was faster while finding nothing on Google, I put this benchmark together.

Function Time Comparison
while() 0.921 seconds (38% faster)
for() 0.916 seconds (38.4% faster)
for() optimized 0.793 seconds (46.6% faster)
foreach() 1.486 seconds

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?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;
 
	while ($j >= 0)
	{
		$test_array[$j];
 
		$j--;
	}
}
echo 'while() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
$time_start = getmicrotime();
for ($i=0; $i<1000000; $i++)
{
	$length = count($test_array)-1;
 
	for ($j=$length; $j>=0; $j--)
	{
		$test_array[$j];
	}
}
echo 'for() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
$time_start = getmicrotime();
for ($i=0; $i<1000000; $i++)
{
	for ($j=count($test_array)-1; $j>=0; $j--)
	{
		$test_array[$j];
	}
}
echo 'for() optimized :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
$time_start = getmicrotime();
for ($i=0; $i<1000000; $i++)
{
	$reversed_array = array_reverse($test_array, true);
 
	foreach ($reversed_array as $key=>$value)
	{
		// Nothing
	}
}
echo 'foreach() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
?>


Comments

Top

Leave a Reply

Comments welcome! Name & email required; email always kept private. Please use basic markup. Wrap code with <code> tags.