Local Variable Cost

../_images/local-variable-cost.png

Local variables in PHP methods cost something. Not much, but a bit. And, more importantly, they cost memory even when not used.

Check this simplistic proof of concept: a recursive function, with one local variable. Not, let’s run this script until it dies of memory exhaustion. For that to be a reasonable even, the memory_limit must be set as low as possible: 2.1Mb.

0 local variable: 10918

1 local variable: 8932

2 local variables: 7559

3 local variables: 6550

4 local variables: 5777

5 local variables: 5170

6 local variables: 4678

7 local variables: 4271

21 local variables: 2651

These values do not change with PHP versions: middle versions from 8.0 to 8.6 were tested (and 8.5 did seg fault on OSX)

Also, the numbers of iteration do not change with the default value, except when using an object as initial value.

The number of iteration did not change when a variable was initialized several times: $a = 1; $a = 1; $a = 1 counted as three distinct variable allocation, as if they were distinct.

In the end, it is a micro-optimisation, as it needs thousands of calls to eat up 2M of RAM. But it might be interesting to monitor the number of local variables in a methods, as the worst offenders use up to 350 of them… That must count.

See Also

PHP Features