12

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?

keithjgrant
  • 12,421
  • 6
  • 54
  • 88

5 Answers5

21

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;
}
Kendall Hopkins
  • 43,213
  • 17
  • 66
  • 89
  • 1
    Good call. That's where the real problem lies. It's an older piece of code that could probably use the optimization check. – keithjgrant Mar 18 '10 at 22:23
  • A side question: Isn't using many (local) static variables, specific to an individual function causing overhead on RAM (since they will be kept in memory until the script executes fully) or are all variables kept in memory in PHP? – Dzhuneyt Jun 10 '13 at 09:13
  • 1
    @ColorWP.com Yes this basically define a memory leak, but that's the point. This is similar to the singleton pattern. – Kendall Hopkins Jun 10 '13 at 16:18
2

This should work in your (quite simple) case:

function your_function() {
    static $output;

    if (!isset($output)) {
       $output = 'A very expensive operation';
    }

    return $output;
}

As for a global caching mechanism, you may use a method similar to this one.

Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118
2

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
}
user187291
  • 53,363
  • 19
  • 95
  • 127
0

Here is quite shorter approach:

function stuff()
{
    static $smthg = []; // or null, or false, or something else
    if ($smthg) {
        return $smthg;
    }

    // filling $smthg goes here 
    // with a lot of 
    // code strings

    return $smthg;
}
Oleg Neumyvakin
  • 9,706
  • 3
  • 58
  • 62
-2

How about:

if (!isset($i))
{
    static $i = moderatelyExpensiveFunctionCall();
}
Amy B
  • 17,874
  • 12
  • 64
  • 83