🐘 PHP Advanced

What is PHP's memory management and how to optimize it?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized PHP deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

PHP allocates memory from the OS using its own memory manager, which maintains pools of pre-allocated blocks for efficient allocation. The default memory limit is 128MB (memory_limit in php.ini). Check current usage: memory_get_usage(). Optimization techniques: unset variables when done (unset($largeArray)), use generators instead of building large arrays in memory, process large datasets in chunks rather than loading everything, use streams for large file processing, avoid keeping database result sets in memory (use cursors), enable OPcache to reduce repeated parsing overhead. For CLI scripts processing millions of records, consider disabling the query log in ORM and batching operations. Memory profiling tools: Xdebug memory profiler, Blackfire.io.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.