[UPHPU] performance hit recalling functions?

Joseph Scott joseph at josephscott.org
Sat Dec 19 22:34:26 MST 2009


On Fri, Dec 18, 2009 at 11:38 PM, Wade Preston Shearer
<wadeshearer.lists at me.com> wrote:
> If you are going to be calling a function (such as count() a few times
> within a script, is there any performance benefit to calling it once
> at the beginning, storing the result in a value and then using the
> value instead of recalling the function each time?


My understanding was that if you were going to use the count more than
once then it's better to store it in a separate variable instead of
having PHP recalculate the count over and over.

But it's fair to make an attempt to figure out if that is really the
case.  I put together a simple test case:

multi count: http://pastebin.com/f65053a09
single count: http://pastebin.com/f51c59b7c

Then used VLD to see the op code count for each method:

multi count: 75 ops
single count: 64 ops

So PHP has to do 11 more operations when calling count() multiple
times vs. once and storing it in a variable.

Next I added a call to memory_get_peak_usage() at the end of each
script to see if there was a memory difference.  The actual number for
each isn't important here, just the difference between the two:

multi count: 115,720 bytes
single count: 115,704 bytes

Calling count() multiple times adds 16 bytes to the memory usage.

And of course did some actual timing comparisons to see if run time
showed any difference.  I looped through just the count/if section of
code 100,000 times to make any difference obvious.  That way the array
was created just once, leaving the time measurement to focus on count
issue.  The run times were very consistent, with only very tiny
differences:

multi count: 0.28717994689941 seconds
single count: 0.10203385353088 seconds

The multi count time was more than double the single count time,
adding 0.185 seconds.

Conclusion, running count multiple times is more costly that doing it
once and saving result in a variable.  The difference is small, but
the single count method clearly wins; fewer ops, less memory and runs
faster.  The difference is small, on an individual case insanely
small, but there is certainly a difference.



-- 
Joseph Scott
joseph at josephscott.org
http://josephscott.org/


More information about the UPHPU mailing list