Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable for optimization

I'm wondering if I can use a static variable for optimization:

public function Bar() {
    static $i = moderatelyExpensiveFunctionCall();
    if ($i) {
        return something();
    } else {
        return somethingElse();
    }
}

I know that once $i is initialized, it won't be changed by by that line of code on successive calls to Bar(). I assume this means that moderatelyExpensiveFunctionCall() won't be evaluated every time I call, but I'd like to know for certain.

Once PHP sees a static variable that has been initialized, does it skip over that line of code? In other words, is this going to optimize my execution time if I make a lot of calls to Bar(), or am I wasting my time?

like image 832
keithjgrant Avatar asked Mar 18 '10 21:03

keithjgrant


People also ask

What are optimization variables?

An optimization variable is a symbolic object that enables you to create expressions for the objective function and the problem constraints in terms of the variable.

Are static variables more efficient?

Using static variables may make a function a tiny bit faster. However, this will cause problems if you ever want to make your program multi-threaded. Since static variables are shared between function invocations, invoking the function simultaneously in different threads will result in undefined behaviour.

What are static variables give example?

1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can't be used for this purpose.

What are static variables?

In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program.


2 Answers

I find it easier to do something like the code below. That way the caching is done globally instead of per implementation of the function.

function moderatelyExpensiveFunctionCall()
{
   static $output = NULL;
   if( is_null( $output ) ) {
     //set $output
   }
   return $output;
}
like image 140
Kendall Hopkins Avatar answered Oct 02 '22 14:10

Kendall Hopkins


static $i = blah() won't compile, because php doesn't allow expressions and function calls in static initializers. You need something like

function foo() {
   static $cache = null;

   if(is_null($cache)) $cache = expensive_func();

   do something with $cache
}
like image 23
user187291 Avatar answered Oct 02 '22 14:10

user187291