使用 JSBase.h 中的以下函数:
/*!
@function JSGarbageCollect
@abstract Performs a JavaScript garbage collection.
@param ctx The execution context to use.
@discussion JavaScript values that are on the machine stack, in a register,
protected by JSValueProtect, set as the global object of an execution context,
or reachable from any such value will not be collected.
During JavaScript execution, you are not required to call this function; the
JavaScript engine will garbage collect as needed. JavaScript values created
within a context group are automatically destroyed when the last reference
to the context group is released.
*/
JS_EXPORT void JSGarbageCollect(JSContextRef ctx);
您可以获得JSContextRef
从你的JSContext
, using JSGlobalContextRef
只读属性。
Update
我发现了 WebKit 的下一个变化 -bugs.webkit.org/show_bug.cgi?id=84476 http://bugs.webkit.org/show_bug.cgi?id=84476:
JSGarbageCollect 不应同步调用collectAllGarbage()。
相反,它应该通知 GCActivityCallback 它已放弃
一个对象图,它将设置计时器在某个点运行
JSC可以根据自己的政策决定未来的发展。
这解释了为什么以前的解决方案不能按预期工作。
深入研究 WebKit 源代码,我发现了另一种有趣的方法。请尝试以下代码:
JS_EXPORT void JSSynchronousGarbageCollectForDebugging(JSContextRef ctx);
@interface JSContext (GarbageCollection)
-(void)garbageCollect {
JSSynchronousGarbageCollectForDebugging(self.JSGlobalContextRef);
}
@end
只需致电garbageCollect
方法对你的JSContext
之后的例子。我在 iOS 本地尝试过,似乎有效。