An addendum, as a few people have pointed out to me on Twitter:
This applies to runtime behavior. PHP has another optimization where, if you define an array as a const
it gets placed in shared memory with the code, so the net memory cost to each process using that array is 0.
That's really only applicable if:
- You are generated compiled code.
- The compiled array contains only scalars and arrays (no objects or closures).
- The compiled array will never be modified at runtime.
In that case, a const
big nested array may indeed be better both for CPU and memory.
The runtime builder for that compiled code, though, is still better off using objects for memory efficiency so that you can produce that compiled code.
As always, context matters. :-)