4 ms·
I'd love to see a benchmark of: for ($i = 0; $i < count($users); $i++) vs foreach($users as $user)
by nodesocket 14y ago
I'd love to see a benchmark of:
for ($i = 0; $i < count($users); $i++)
vs
foreach($users as $user)
- robryan 14y agoThere are some similar benchmark here: http://www.phpbench.com/ http://www.phpbench.com/ Intuitively the for loop should be a lot fast as it isn't assigning anything each loop. Although in your example it may be slower because the count($users) would be ran on each iteration of the loop.
- josegonzalez 14y agoIt only assigns $user in a foreach when the $user is modified, or if you are trying to outsmart PHP-core and use & to pass it as a reference.
- encoderer 14y agoI get what you mean, but it might be helpful to translate it for everybody else: Foreach is doing an assignment in each iteration, robryan is right. But PHP variables are copy-on-write so $user is, until modified, just an entry in the symbol table which is very fast. And that for() loop also has an assignment -- the incrementer.
- nodesocket 14y agoI just coded up a benchmark and posted the ProTip on coderwall. http://coderwall.com/p/il1tog http://coderwall.com/p/il1tog
- encoderer 14y agoYou're re-calculating the count() on each iteration. Of course it's slower. Fix that: for($i = 0; $count = count($elements); $i < $count; $i++) { }
- nodesocket 14y agoYeah I know, done purposefully to see how MUCH slower this is. This is how the majority of code is written in the wild, rarely do you see the `count()` pulled outside of the `for()`.
- firlefans 14y agoThis is simply unfair, should the language maintainers be held accountable for user behaviour? A more interesting and fairer topic is whether PHPs count() is considerably slower than python's len()