【发布时间】:2016-02-28 23:13:00
【问题描述】:
有没有办法强制 iOS(或 Mac OS)JavaScriptCore VM 垃圾收集器运行?我只需要它来测试内存泄漏,所以私有 API 就可以了。
【问题讨论】:
标签: ios macos garbage-collection javascriptcore
有没有办法强制 iOS(或 Mac OS)JavaScriptCore VM 垃圾收集器运行?我只需要它来测试内存泄漏,所以私有 API 就可以了。
【问题讨论】:
标签: ios macos garbage-collection javascriptcore
使用 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);
您可以使用JSGlobalContextRef 只读属性从您的JSContext 获取JSContextRef。
更新
我发现 WebKit 的下一个变化 - 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
之后,只需在您的 JSContext 实例上调用 garbageCollect 方法即可。我已经在 iOS 上本地尝试过,它似乎可以工作。
【讨论】:
extern "C" JSSynchronousGarbageCollectForDebugging(JSContextRef ctx); JS_EXPORT 宏已更改,或者取决于使用此代码的位置(我正在使用它在 c++ ios 14 中)