【问题标题】:Force garbage collection of JavaScriptCore virtual machine on iOS在 iOS 上强制对 JavaScriptCore 虚拟机进行垃圾回收
【发布时间】:2016-02-28 23:13:00
【问题描述】:

有没有办法强制 iOS(或 Mac OS)JavaScriptCore VM 垃圾收集器运行?我只需要它来测试内存泄漏,所以私有 API 就可以了。

【问题讨论】:

    标签: ios macos garbage-collection javascriptcore


    【解决方案1】:

    使用 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 上本地尝试过,它似乎可以工作。

    【讨论】:

    • 谢谢鲍里斯。不幸的是,看起来这实际上并没有触发垃圾收集 - 如果我调用这个方法没有区别,垃圾收集器似乎只有在使用的内存超过阈值时才会执行。
    • 有效! (实际上,只需声明 JSSynchronousGarbageCollectForDebugging 然后使用 ctx.JSGlobalContextRef 从代码中运行它就足够了。)谢谢!
    • @silyevsk,很高兴为您提供帮助 :)
    • 对于任何寻找这个,但发现该符号仍然丢失的人...... extern "C" JSSynchronousGarbageCollectForDebugging(JSContextRef ctx); JS_EXPORT 宏已更改,或者取决于使用此代码的位置(我正在使用它在 c++ ios 14 中)
    猜你喜欢
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2021-03-18
    • 2011-01-26
    • 2010-09-16
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多