DEV Community

Mohcin Bounouara
Mohcin Bounouara

Posted on

PHP note: For Loop Performance

About a year ago I started to writing code “BUT NOT JUST FOR WRITING IT”, I focused on to trying to fully understand what I’m about to write, in the whole software life cycle and I was giving attention to the performance, speed, and clean code.

So I was trying to improving my “PHP For Loop”.

I was repeating myself and write for loop on this way below:

$array = [0, 1, 2, 3, 4];

for($i = 0; $i < count($array); $i++) {
      print_r ($i);
      echo '<br/>';
}
Enter fullscreen mode Exit fullscreen mode

The above way of writing for loop is WRONG. Why?

In every loop the Count function is called, and that is code overhead, we have just 5 items in the the array, imagine that we have hundred that will absolutely affect the performance of the script.

Let’s try to improve our loop:

$array = [0, 1, 2, 3, 4];
$j = count($array);
for ($i=0; $i < $j; $i++) {
  print_r ($i);
  echo '<br/>';
}
Enter fullscreen mode Exit fullscreen mode

Let’s calculate for loop execution time in seconds and do comparison;

The first script: Executed in 4.0531158447266E-6 seconds

The second script: Executed in 3.0994415283203E-6 seconds

Those notes is about small scripts, try to imagine working on large-scale apps or websites. Making attention to these things will improve your code and totally improve your vision as a software developer or web developer.

Discussion (0)