PHP在单个请求中分配的内存总是在最后释放吗?
我对 PHP 中的内存泄漏有点困惑。
我读到,由于 Zend 内存管理器,PHP 会自动释放每个请求中使用的内存: http://www.webreference.com/programming/php_mem/2.html
但我看到很多人和主题(甚至在 SO 中)都担心 PHP 和内存泄漏。
所以我觉得我失去了一些东西。
PHP 中不同请求之间是否可能存在内存泄漏?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不同请求之间的 PHP 脚本不可能出现内存泄漏(使用默认 Apache 配置时),因为一个请求中使用的变量和代码会在该请求结束时释放,并且 PHP 的内存分配器会为下一个请求重新启动。然而,PHP 解释器或扩展中的错误可能会单独泄漏内存。
一个更大的问题是 Apache 子进程内部有 PHP 的内存空间。它们会膨胀分配 PHP 脚本的峰值内存使用量,然后维持此内存分配,直到子进程被终止(一旦进程要求内核分配一部分内存,该内存将不会被释放,直到进程终止) )。有关为什么这是一个问题以及如何解决它的更详细说明,请参阅我在 服务器故障。
脚本中的内存泄漏(变量未设置且 PHP 垃圾收集器失败)非常罕见 - 大多数 PHP 脚本运行几百毫秒,而这通常不足以让严重的内存泄漏显现出来。
您可以使用
memory_get_usage 监控 PHP 脚本使用了多少内存()
和memory_get_peak_usage()
- 在 PHP 手册。本文中详细解释了 PHP 的内存管理。
编辑:您可以使用
httpd -l
确定编译到Apache的模块 - 默认值因操作系统发行版和存储库配置而异。将 PHP 与 Apache 连接的方法有很多 - 最详细的此处 。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()
andmemory_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.