- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到过several places人们打电话的地方 collectgarbage() 两次完成所有未使用的对象。
这是为什么呢?为什么一次调用还不够?为什么不打三个电话?
当我尝试以下代码(在 Lua 5.2 上)时,只需调用一次 collectgarbage
即可最终确定该对象(这意味着:它的 __gc
被调用):
do
local x = setmetatable({},{
__gc = function() print("works") end
})
end
collectgarbage()
os.exit()
这是否意味着一次调用就足够了?
最佳答案
Programming in Lua 第 3 版 §17.6 Finalizers 对此进行了解释。简而言之,就是因为复活。
终结器是与对象关联的函数,当该对象即将被收集时调用该函数。 Lua 使用 __gc
元方法实现终结器。
问题是,当调用终结器时,在某些情况下对象必须处于事件状态。 PiL 用这个例子解释了这一点:
A = {x = "this is A"}
B = {f = A}
setmetatable(B, {__gc = function (o) print(o.f.x) end})
A, B = nil
collectgarbage() --> this is AThe finalizer for
B
accessesA
, soA
cannot be collected before the finalization ofB
. Lua must resurrect bothB
andA
before running that finalizer.
复活是调用collectgarbage
两次的原因:
Because of resurrection, objects with finalizers are collected in two phases. The first time the collector detects that an object with a finalizer is not reachable, the collector resurrects the object and queues it to be finalized. Once its finalizer runs, Lua marks the object as finalized. The next time the collector detects that the object is not reachable, it deletes the object. If you want to ensure that all garbage in your program has been actually released, you must call
collectgarbage
twice; the second call will delete the objects that were finalized during the first call.
关于lua - 为什么我们需要调用Lua的collectgarbage()两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28320213/
我注意到在 VS2010 javascript intellisence 中有一个名为 CollectGarbage() 的方法。 这是一种仅适用于 IE 的方法吗? 什么时候使用? 使用它有什么优点
我是lua的初学者。我正在尝试分析我的应用程序的内存使用情况。当我从 lua REPL 中反复调用 collectgarbage('count') 时,返回的值不断增加。 th> collectgar
我最近正在尝试跟踪我们项目中的 lua 内存使用情况,我遇到了使用 lua_Alloc 自定义分配器来完成此任务的想法。好吧,分配器代码看起来很简单,而且工作正常。 但很快,这个小功能就遇到了两个挑战
我是一名优秀的程序员,十分优秀!