Adding One String Key to a PHP Array Can Silently Consume 25 MB Extra Memory

A developer refactoring legacy PHP code discovered a significant memory cost tied to how PHP internally handles arrays. A packed array of one million integers uses about 16.8 MB in PHP 8.4, but adding even a single string key forces PHP to convert it into a full hash table, jumping memory usage to nearly 42 MB. This conversion adds roughly 25 MB of overhead and is irreversible — unsetting the key does not reclaim the memory. The same penalty applies when filling an array with sequential integer keys in reverse order, as PHP treats out-of-order insertion as a hash table rather than a packed list. The findings highlight how PHP's internal array optimizations can silently break under common coding patterns, with real consequences for memory-heavy workloads like processing large database result sets.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in