tags:

views:

58

answers:

6

Hi, basicly I've got an array and want to call the same function for each element. Which way 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

A: 

This is the kind of micro-optimization that most likely does not matter. Do whatever leads to cleaner code.

If you know (know, not guess) that this specific piece of code is causing performance problems, then the second alternative is almost certainly slightly faster.

Michael Borgwardt
Is this because the first one makes calls to a separate function however many times the foreach is called, while the second one stays within the function until the foreach is done?
abelito
@abelito: You're right. Calling a function involves a certain overhead, though it's usually only significant when the function does very little work (such as a simple getter or setter), and compilers can often eliminate the overhead by inlining the function call.
Michael Borgwardt
A: 

They are essentially the same, and any time execution difference will be negliable. It comes down to preference.

Tom Gullen
+2  A: 

Probably slightly faster with the loop inside the function, as there is a (slight) cost to each function call. However, it won't make much difference.

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

You should write it so it is clear, then if it's too slow, figure out where it's slow and optimize that.

Blorgbeard
second that....
pinaki
A: 

I dont think there would be much of a difference between the two anyway, but from what I recollect of function stack calling, the first method should take longer.

pinaki
A: 

In every language I know, using loops is faster, because of the operations involved when calling a function (like adding it to the stack).

However, you should not think about the performance before the actual performance issues arise. Think in terms of design, code clarity, and low maintenance efforts.

Pierre Gardin
A: 

In short: The second one should be faster.

In detail: When a function is called, the function arguments, local variables and the return address is pushed on the internal stack and popped off the stack when the function call is done. That means your first variant will cause these stack operations for every value in your array while the second variant will only cause these stack operations once.

Gumbo