Alex Rivera | Logout

Static variable for optimization

Asked 2010-03-18T21:49:52.730
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?

Edit
Report

1 Answer

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.

answered 2013-04-20T16:57:18.017

Your Answer