Skip to content
Advertisement

Is it better call a function every time or store that value in a new variable?

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:

JavaScript

With an array of 9 items:

JavaScript

With a array of 180 items:

JavaScript

With a array of 3600 items:

JavaScript

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement