PHP 的内存问题 (5)
调用 unset()
是否释放与该对象关联的内存?在某些情况下,我发现自己正在处理大型关联数组,并且我想在完成后删除它们(释放内存以创建新数组)。
Does calling unset()
free the memory that was associated with that object? There are a couple cases where I find myself handling large associative arrays and I would like to remove them when done (freeing up memory to create new ones).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的。
使用
memory_get_usage()
:更多资源:
引用后面的链接:
Yes it does.
Check for yourself using
memory_get_usage()
:More Resources:
Quoting from later link:
unset()
在 php 中“释放”内存,但它让垃圾收集器决定何时实际释放所述内存。因此,内存会根据需要或方便地释放(在 PHP 耗尽可用内存之前)。一个主要的警告是注意您没有尝试在本地范围内
unset()
全局变量。即使是通过引用传入的变量,当在函数的语言环境中执行此操作时,也只会取消设置其本地引用。为了真正使内存可用,任何unset()
都应该在该变量的适当范围内完成。unset()
does "free" memory in php, but it lets the garbage collector decide when to actually release said memory. Thus, memory is freed on an as-needed or as-convenient basis (prior to PHP running out of available memory).A major caveat is to watch that you're not attempting to
unset()
global variables within a local scope. Even variables passed in by reference will only have their local referencesunset
when this is performed in a function's locale. To truly make memory available, anyunset()
should be done in that variable's appropriate scope.它不会立即释放内存,但它允许垃圾收集器执行此操作。
It doesn't free the memory immediately, but it allows the garbage collector to do it.
通过取消设置变量,您将其“引用计数”设置为 0。这允许 Zend 引擎在内存中移动内容,并且它知道它可以覆盖内存中的变量区域,因为它的引用计数为 0。
这发生在之前甚至还想到了垃圾收集。现在你已经知道了,unset() 实际上可以在应用程序的生命周期中为你提供帮助。
By unsetting a variable you're setting it's "refcount" to 0. This allows for the Zend Engine to shift things about in memory and it knows that it can overwrite your variables area in memory as it has a refcount of 0.
This occurs before garbage collection is even thought of. So there you have it, unset() does actually help you out during the lifecycle of your app.
不,它不一定会释放任何东西。它只是减少了引用计数。
示例:
挑剔角落:从技术上讲,这里有两个引用计数——对象的和 zval 的。在整个程序中,对象的引用计数只有 1,实际上是 zval 的引用计数在赋值和调用
unset
中发生了变化。No, it doesn't necessarily free anything. It just decreases the reference count.
Example:
Nitpick corner: technically, there are two reference counts in play here -- the object's and the zval's. The reference count of the object is only 1 throughout the program, it's actually the reference count of the zval that's changed in the assignment and in the call to
unset
.在 PHP > 5.3.0 中, gc_collect_cycles() 函数强制收集任何现有的垃圾周期。
In PHP >5.3.0, the gc_collect_cycles() function forces collection of any existing garbage cycles.