Why is it bad to call a function in a for loop condition?

Recently I asked the application architect at work to consider the php script that I wrote to automate some of the tasks that I perform weekly in our support department.

In his review, he stated

## Loops

Your loops are good, you didn't do anything bad like calling functions in the condition

for ($i=0; $i < count($array); $i++); is BAD

Honestly, I was never tempted to do this in my code before, but it made me wonder why it would be bad.

I guess this is because the result of the function can be any value at all, and it seems like the perfect way to create an infinite loop and just generally causes unexpected behavior.

I tried a search on Google but could not find any suitable results, so I ask:

Why is it bad to call a function in a for loop condition?

Note count($array) in the comment itself, for me, gimme. Of course, you just want to cache this. In particular, I mean the use of other more complex functions.

For those who are probably wondering: โ€œWhy not just ask the guy who wrote it,โ€ he is very busy and has already taken the time to help me, I donโ€™t want to push too much โ€œNow please explain all your comments to me?โ€

+5
source share
3 answers

There are several reasons I can think of:

  • The return value of a function may change, so you cannot be sure that your loop will remain finite.
  • The return type is not supported in some languages, so you have another option for undefined behavior
  • It is usually less efficient (especially in the count() example)
  • This reduces readability because the developer now needs to review and understand the function in order to know how many times the loop needs to run.
  • I can't come up with ANY legitimate examples of why you really need the return value of a function, every time a condition is evaluated
  • The number of iterations cannot be (easily) determined at run time because the function must be called again at the end of each iteration
+4
source
 for ($i=0; $i < count($array); $i++); //is not efficient 

Yes, this is not efficient to use, because it is called in every iterative function, which is not very good. You need to execute this function once.

 $count = count($array); for ($i= 0; $i < $count; $i++); //is much efficient 

Because in this code count function will be executed once. In the previous count code, the function is executed several times.

+4
source

Itโ€™s better to count the values โ€‹โ€‹in advance, because if you put it in a loop, the function will execute at each iteration to check if the condition is met.

In this example, the count function is not too heavy and will not slow down your program (unless it is an array), but pay attention to larger functions.

+3
source

Source: https://habr.com/ru/post/1243032/


All Articles