Looping into a function or calling a function multiple times, which is faster?

Basically, I have an array and you want to call the same function for each element. How is it faster?

foreach($elemeents as $element){
    callFunction($element);
}

OR

function callFunction($leements){
    foreach($elements as $element){
        //do something
    }
}

thanx in advance, im just a beginner

+3
source share
6 answers

Probably a little faster with a loop inside the function, since there is a (small) cost to each function call. However, this will not make much difference.

This is truly premature optimization, and the root of all evil .

You have to write it so that it is clear, then if it is too slow, find out where it is slow and optimize it.

+3
source

-, , , . , .

(, ), , .

0

, , , . .

0

, , , , .

0

, , , - , (, ).

. , .

0

: .

Details: When a function is called, function arguments, local variables, and the return address are pushed onto the internal stack and unloaded from the stack when the function is called. This means that your first option will result in these stack operations for each value in your array, while the second option will only result in these stack operations once.

0
source

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


All Articles