Reputation: 30761
Suppose I want to iterate over an array and either I never look at the values, or I am setting things in them, so I only want the keys. Which is quicker:
// Set a variable each iteration which is unused.
foreach ($array as $key => $value) {
$array[$key]['foo'] = 'bar';
}
// Call array_keys() before iterating.
foreach (array_keys($array) as $key) {
$array[$key]['foo'] = 'bar';
}
Upvotes: 19
Views: 8820
Reputation: 98
People need to stop prioritizing questioning the motive of the OP.
I did a simple microtime test and noticed barely any noteable difference in execution time.
The method - creating the test-array:
$arr = array();
for($i = 0; $i<10000; $i++){
$arr[] = mt_rand(0, PHP_INT_MAX);
//NOTE: I also tested setting values in random keys, no measurable difference
}
Then use that array for testing:
//Method 1
$start = microtime(true);
foreach(array_keys($arr) as $k){
$arr[$k] = 0; //Do something
}
$end = microtime(true);
echo 'we spent '.($end - $start).' seconds doing this.';
Here is the code for the other method testing (ran this separately, or results varied even more)
//Method 2
$start = microtime(true);
foreach($arr as $k => $v){
$arr[$k] = 0; //Do something
}
$end = microtime(true);
echo 'we spent '.($end - $start).' seconds doing this.';
My timings were around 2 milliseconds runtime for both. I guess my system isn't stable enough for consistent measures of microseconds. I could not determine if one was faster than the other.
I also tested running each foreach 1000 times with a smaller array to measure the method itself, but I just got the same 2 milliseconds result.
So what does this mean? Based on these simple tests, the choice of method is pointless in regards to performance. Maybe you can measure a tiny improvement with one method over another if you are running extremely large arrays on extremely stable systems, or running extremely many foreach-loops the one way the other.
Upvotes: 2
Reputation: 227180
I think this would also work, and may be quicker:
foreach ($array as &$value) {
$value['foo'] = 'bar';
}
UPDATE: I did a little test, and it seems this is faster. http://codepad.org/WI7Mtp8K
Upvotes: 13
Reputation: 72961
Leaving aside that the second example is contrived. Meaning, as Ashley Banks noted, why would you be doing this?
The first example would be more performant of the two. The second has the overhead of the additional function call to array_keys()
.
Check out the PHP Benchmark for additional performance tests. When in doubt, benchmark it yourself with microtime()
.
Upvotes: 3