2

I'm genuinely curious... is the impact on performance remotely concerning when using count($arr) over and over in a loop, vs. storing the count first, and then iterating?

In other words, does this:

$count = count($arr);
for($i = 0; $i < $count; $i++) { ... }

Perform any better than this:

for($i = 0; $i < count($arr); $i++) { ... }

I have never noticed a performance issue, but my arrays are usually relatively small (maybe a few hundred items at most). But for very large arrays, does it make a difference whether you store the count before iterating or re-calculate the count every time the loop runs?

David Mordigal
  • 399
  • 3
  • 19

3 Answers3

0

If You put count as second way count() will run every iteration.

First way is preferred or sth like this:

for($i=0, $count=count($items); $i<$count; $i++)
{
    // ....
}
Pyton
  • 1,291
  • 8
  • 19
0

I prefer to use the first approach where you store the count first and then you use that variable inside loop.

$count = count($arr);
for($i = 0; $i < $count; $i++) { ... }

This way count() is called only once and not at every iteration.

Secondly,When you use count() inside loop like below,

for($i = 0; $i < count($arr); $i++) { ... }

count() is called every time a loop is iterated over.So for Example if your array contains 100 values than count() will be called 100 times where in first approach it is only called once to return count value as 100

So instead of calling it every time and returning same value over and over again, first approach is preferable. When your array size if much bigger at that time you will notice performance difference in both approach.

Saurabh
  • 776
  • 1
  • 5
  • 15
0

It makes trace difference to performance because calling count() on an array has constant time complexity. The only time it would make a difference is if you are manipulating the content of that array within the loop, in which case the size of the array may change with each iteration, which will usually not be what you want.

Quolonel Questions
  • 6,603
  • 2
  • 32
  • 33