view Phoenix's home page
Phoenixblogbookmarksrss feeds
ecastr . sign in . register

Advanced PHP Optimization Tips (Chapter 2: Iterate over arrays)

It's time to continue with my attempts to find which is the better (most optimized) way to program in PHP. In previous post I took a look at string concatenating. This time I'm going to iterate over arrays. The main goal is to get the key and the value of each item in an array.

Let's start:

Iterate over arrays test:

This is the target array

$values = array("a", "b", "c", "d", "e", "f");

and these are my test cases

Case 1:
foreach($values as $k=>$v){
}

Case 2:
for($k = 0; $k < sizeof($values); $k++){
$v = $values[$k];
}

Case 3:
$count = count($values);
for($k = 0; $k < $count; $k++){
$v = $values[$k];
}

Case 4:
$count = sizeof($values);
for($k = 0; $k < $count; $k++){
$v = $values[$k];
}

Results:

Case 2 is 3 times slower than Case 1

Case 3 is 1.5 times slower than Case 1

Case 4 is 1.5 times slower than Case 1

This result are not so spectacular as the result in string concatenating article, that's because reading a variable is faster than writing. Curious how much faster? So let't test this too.

Bonus test results:


writing 50 letter strings into an array is 3 times slower than reading them.


published on 16 nov 07
comments
please sign in to be able to add comments!
tags
recent posts
Advanced PHP Optimization Tips (Chapter 2: Iterate over arrays)
© ecastr 2008 beta  about . blog . toolbar . terms of use . privacy . feedback