开发者

Is the memory allocated by PHP in a single request always released at the end?

I'm a bit confused about the memory leaks in PHP.

I've read that PHP is releasing automatically the memory used in each request thanks to the Zend Memory Manager: http://www.webreference.com/programming/php_mem/2.html

But I see a lot of people and topics (even here in SO) concerned about PHP and memory leaks.

So I feel that I'm losing something.

Is it possible to have memory开发者_如何学运维 leaks in PHP between different requests?


It is not possible to have memory leaks from PHP scripts between different requests (when using the default Apache configuration), as the variables and code used in one request are released at the end of that request and PHP's memory allocator starts afresh for the next request. Bugs in the PHP interpreter or extensions could leak memory separately, however.

A much greater problem is that Apache child processes have PHP's memory space inside them. They swell to allocate the peak memory usage of a PHP script and then maintain this memory allocation until the child process is killed (once a process has asked the kernel to allocate a portion of memory, that memory won't be released until the process dies). For a more detailed explaination of why this is a problem and how to combat it, see my answer on Server Fault.

Memory leaks in a script, where variables are not unset and the PHP garbage collector fails, are very rare - most PHP scripts run for a few hundred milliseconds, and this is not generally enough time for even a serious memory leak to manifest.

You can monitor how much memory your PHP script is using with memory_get_usage() and memory_get_peak_usage() - there is also a good explanation on memory usage and how to program defensively in the PHP manual.

PHP's memory management is explained in detail in this article.

edit: You can determine the compiled in modules to Apache with httpd -l - defaults vary by OS distribution and repository configuration. There are plenty of ways to interface PHP to Apache - most detailed here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜