[thelist] declaring once verse not

Simon Willison cs1spw at bath.ac.uk
Thu Aug 14 09:00:10 CDT 2003


Hi Gary,

> This got me wondering ... does it take less processor usage to set a
> variable once and call it everytime, or to just repeat the month function
> for each use.
> 1.
> curmonth = month(date())
>     check curmonth
>     check curmonth
>     check curmonth
> 2.
>     check month(date())
>     check month(date())
>     check month(date())

> Though there is probably no great difference in this one use, would it add
> up if one style is used alot over another?

The first method is definitely more efficient. Each month(date()) call
is two function calls - if you store the result of the call in a
variable each further reference to curmonth is just a simple variable
lookup, with no function calls required. A call to a function has a
far higher overhead than accessing a variable.

This doesn't matter at all for simple things like your example, as the
speed difference will be negligible. Once you start looping several
thousand times the performance hit of all those unnecessary repeated
function calls becomes something to worry about.

On a related note, here's a tip:

<tip type="PHP" author="Simon Willison">
If you are looping through a large array, the most efficient way to do
it is using the following idiom:

for ($i = 0, $j = count($array); $i < $j; $i++) {
    // Do something with $array[$i];
}

This is better than the following:

for ($i = 0; $i < count($array); $i++) ...

Because the count() operation is only performed once at the start of
the loop.
</tip>

Cheers,

Simon

-- 
http://simon.incutio.com/



More information about the thelist mailing list