Storing the results of a function in a variable and referencing the variable will almost always be faster, this should be no surprise because instead of executing the function PHP just has to return the variable's value.
In #1 since you only call the function once the function is only executed once, in a loop it is executed once for each loop iteration. Jason On Sat, 2003-03-15 at 21:25, Don Read wrote: > On 15-Mar-2003 CF High wrote: > > Hey all. > > > > Quick question: > > > > If I have a function that, say, prints out the months in a year, and I > > call > > that function within a 10 cycle loop, which of the following is faster: > > > > 1) Have function months() return months as a string; set var > > string_months = months() outside of the loop; then echo string_months > > within > > the loop > > > > -- OR > > > > 2) Just call months() for each iteration through the loop > > > > I'm not sure how PHP interprets option number 1. > > > > Guidance for the clueless much appreciated........... > > > > Easy enuff to test: > > <?php > > function getmicrotime(){ > list($usec, $sec) = explode(" ",microtime()); > return ((float)$usec + (float)$sec); > } > > $time_start = getmicrotime(); > for ($m=1; $m <11; $m++) { > echo date('F', strtotime("2003-$m-1")), '<br>'; > } > echo '<P>A: ', getmicrotime() - $time_start , '<P>'; > > $time_start = getmicrotime(); > for ($m=1; $m <11; $m++) { > $str[]=date('F', strtotime("2003-$m-1")); > } > echo implode('<br>',$str); > echo '<P>B: ', getmicrotime() - $time_start , '<P>'; > > unset($str); > $time_start = getmicrotime(); > for ($m=1; $m <11; $m++) { > $str[]=date('F', strtotime("2003-$m-1")); > } > > while (list(,$v)= each($str)) { > echo $v, '<br>'; > } > echo '<P>C: ', getmicrotime() - $time_start , '<P>'; > > ?> > > On my machine I get numbers like: > A: 0.000907063484192 > B: 0.000651001930237 > C: 0.000686049461365 > > The function call within the loop is slower (contrary to what I > expected), the real question is how much effort do you want to expend to > save 2-3 micro-seconds? > > Regards, > -- > Don Read [EMAIL PROTECTED] > -- It's always darkest before the dawn. So if you are going to > steal the neighbor's newspaper, that's the time to do it. -- Jason Sheets <[EMAIL PROTECTED]> -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php