GGio
GGio

Reputation: 7653

Is it slower to have a function call inside a function when there is no need?

This has been bothering me, lets say I have a function:

public function addItem($item) {
   $this->items[] = $item;
   return $this;
}

and then I have another function like:

public function addItems($items) {
    foreach($items as $item) {
        $this->addItem($item); //IS THIS FASTER OR
        $this->items[] = $item;//THIS?
    }

    return $this;
}

basically I always do the option 1 $this->addItem($item) inside loop but on the other hand it seems to me redundant I could just append item to array essentially it does samething. Just want to know which one is faster if there is any difference in performance.

Upvotes: 0

Views: 87

Answers (4)

sybear
sybear

Reputation: 7784

Function calls require some processor time. So, less function calls -> more performance.

HOWEVER

The main point is that your code remains clear and secure. Such a code is much more important than any performance.

Remember once and forever:

Clear code, clear variable and function names in your code will save you HUGE amounts of time and health.

Your case: addItem() function provides a really good abstraction. Just keep it.

In function addItem() you could do some validation and debug things. Also, it can return true or false indicating success.

Upvotes: 3

TravisO
TravisO

Reputation: 9540

The most important thing I ever learned about benchmarking was

Never believe what anybody tells you about what is faster or slower until you prove it yourself

I have since wrote dozens of benchmarks and proved public opinion wrong many times.

Upvotes: 0

LexLythius
LexLythius

Reputation: 1944

Function jump is in principle slower than direct access (i.e., 1 is faster). That being said:

  1. Don't worry about micro optimizations. Prefer clear, clean, concise and/or flexible code to fast code.
  2. If you use some PHP opcode optimizer, chances are those accesses are inlined. In that case, there would be no difference.

Upvotes: 2

nickb
nickb

Reputation: 59699

This

$this->items[] = $item;

Will always be (minutely) faster than

$this->addItem($item);

Because the second version incurs the overhead of calling a function, whereas the first does not. It is the same reason you should use the first version instead of array_push() for one element. Quoting the manual:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Upvotes: 4

Related Questions