-2

Perhaps this question has been asked several times but I can't find a proper answer here or in Google so apologies if this is a dupe or something like that but here I go...

What's the best way to achieve performance in a loop:

  1. count($var) each time

    for ($i=0;$i<count($var);$i++) {
        // do something
    }
    
  2. put a var outside and use that var:

    $cnt = count($var);
    for ($i=0;$i<$var;$i++) {
        // do something
    }
    

Is there any PHP script or code to show execution times and so on? I mean something for benchmark and see the results on this cases?

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

1 Answers1

1

I'm pretty sure you meant

for ($i=0;$i<$cnt;$i++) {

in the second snippet

yes... it's more efficient to only do the count once.

it can also be done like so

for ($i=0, $cnt=count($var); $i<$cnt; $i++) {
Brad Kent
  • 4,982
  • 3
  • 22
  • 26