php - Exploding an array within a foreach loop parameter
foreach(explode(',' $foo) as $bar) { ... }
vs
$test = explode(',' $foo);
foreach($test as $bar) { ... }
In the first example, does itexplode
the$foo
string for each iteration or does PHP keep it in memory exploded in its own temporary variable? From an efficiency point of view, does it make sense to create the extra variable$test
or are both pretty much equal?
Answer
Solution:
I could make an educated guess, but let's try it out!
I figured there were three main ways to approach this.
My hypotheses:
Approach
Here's my test script:
And here are the three versions:
1)
2)
3)
Results
Conclusions
Looks like some assumptions were disproven. Don't you love science? :-)
explode()
inline without pre-assignment, it's a fair bit slower for some reason.strtok()
every iteration. More on this below.In terms of number of function calls,
explode()
ing really tops tokenizing. O(1) vs O(n)I added a bonus to the chart where I run method 1) with a function call in the loop. I used
strlen($val)
, thinking it would be a relatively similar execution time. That's subject to debate, but I was only trying to make a general point. (I only ranstrlen($val)
and ignored its output. I did not assign it to anything, for an assignment would be an additional time-cost.)As you can see from the results table, it then becomes the slowest method of the three.
Final thought
This is interesting to know, but my suggestion is to do whatever you feel is most readable/maintainable. Only if you're really dealing with a significantly large dataset should you be worried about these micro-optimizations.
Answer
Solution:
In the first case, PHP explodes it once and keeps it in memory.
The impact of creating a different variable or the other way would be negligible. PHP Interpreter would need to maintain a pointer to a location of next item whether they are user defined or not.
Answer
Solution:
From the point of memory it will not make a difference, because PHP uses the copy on write concept.
Apart from that, I personally would opt for the first option - it's a line less, but not less readable (imho!).
Answer
Solution:
Efficiency in what sense? Memory management, or processor? Processor wouldn't make a difference, for memory - you can always do
$foo = explode(',', $foo)