I use often the function sizeof($var)
on my web application, and I’d like to know if is better (in resources term) store this value in a new variable and use this one, or if it’s better call/use every time that function; or maybe is indifferent 🙂
Advertisement
Answer
TLDR: it’s better to set a variable, calling sizeof()
only once. (IMO)
I ran some tests on the looping aspect of this small array:
$myArray = array("bill", "dave", "alex", "tom", "fred", "smith", "etc", "etc", "etc"); // A) for($i=0; $i<10000; $i++) { echo sizeof($myArray); } // B) $sizeof = sizeof($myArray); for($i=0; $i<10000; $i++) { echo $sizeof; }
With an array of 9 items:
A) took 0.0085 seconds B) took 0.0049 seconds
With a array of 180 items:
A) took 0.0078 seconds B) took 0.0043 seconds
With a array of 3600 items:
A) took 0.5-0.6 seconds B) took 0.35-0.5 seconds
Although there isn’t much of a difference, you can see that as the array grows, the difference becomes more and more. I think this has made me re-think my opinion, and say that from now on, I’ll be setting the variable pre-loop.
Storing a PHP integer takes 68 bytes of memory. This is a small enough amount, that I think I’d rather worry about processing time than memory space.