PHP variable declarations or function "recall"

926

I got really basic question about variables and function calls. I don't know how to name this question, so couldn't find any answer using search...

So is there somekind performance difference between these two codes:

Example 1:

if($Page->getCurrentPage('id') == 1) {

    foreach($Page->getPagePosts() as $key => $pagePost) {
        include(PATH_TEMPLATES. "post.php");

        if(count($Page->getPagePosts()) - 1 > $key) {
            echo "<hr>";
        } 
    }
}

Example 2:

$arr = $Page->getPagePosts();
if($Page->getCurrentPage('id') == 1) {

    foreach($arr as $key => $pagePost) {
        include(PATH_TEMPLATES. "post.php");

        if(count($arr) - 1 > $key) {
            echo "<hr>";
        } 
    }
}

Previously I have used Example 2, but not I started thinking if Example 1 is correct too.

101

Answer

Solution:

It depends on your application and scale. Basically it is strongly recommended to ignore trivial performance optimization for the sake of better readability, scalability and maintainability. But there might be instances where you are going to iterate for 1000 times, which then, come costly if you ignore certain standards.

About your first example, in small cases it is OK, but in large calculations, it is best to avoid function-call in any type of loop, and it is best to pass an array to them as there would be no function overhead.

Therefore,

foreach( $users as $user)
{
    //....
}

is better than

foreach( $this->getUsers() as $user)
{
  // ....
}

But there are cases where you can simply ignore such seriousness, for example, in case your site only have two different logos, or at most, 5-records in a table, you can still stick to function-call in the loops:

foreach( $this->siteLogos() as $logo )
{
  // ....
}

While I always read that usingcount() in for-loop must be avoided.

Online benchmarks say that foreach is faster than for-loops, which I'm not sure and invite you to have a research on it.

People are also looking for solutions to the problem: arrays - Use a php function to get the sum per category and counter of scores?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.