简体   繁体   English

垃圾收集未使用的模块

[英]Garbage collect unused modules

I am using dynamic import to load scripts written by the user in the browser. 我正在使用动态导入来加载用户在浏览器中编写的脚本。 I start by placing the script contents into a blob, then I use dynamic import() to load the script as a module. 我首先将脚本内容放入blob中,然后使用动态import()将脚本作为模块加载。 Over time, I expect these scripts to change and be destroyed, and thus for the corresponding modules to be garbage collected. 随着时间的推移,我希望这些脚本能够被更改并被销毁,从而使相应的模块被垃圾收集。 However, based on memory profiling in Chrome, that is not happening. 但是,基于Chrome中的内存分析,这种情况并未发生。

The reason why seems to be related to something called the ModuleMap . 之所以似乎与ModuleMap Here's a screenshot from a memory snapshot I took after all scripts were no longer in use. 这是我在所有脚本不再使用后拍摄的内存快照的截图。

Chrome堆快照

As you can see, the Window object is is providing a retaining path down to these modules. 如您所见,Window对象正在为这些模块提供保留路径。 As long as that is the case, I'm sure to eventually run out of memory, since these modules are created each time the user edits their script. 只要是这种情况,我肯定最终会耗尽内存,因为每次用户编辑脚本时都会创建这些模块。

I'd like to know if there's a way to get Chrome (and other browsers) to unload these modules once they are no longer in use. 我想知道是否有办法让Chrome(和其他浏览器)在这些模块不再使用时卸载这些模块。

I'm getting the sense from this spec that maybe the answer is that you cannot cause modules to be unloaded. 我从这个规范中得到的结论是,答案可能是你无法卸载模块。 This is because any given module must only be parsed once per Document worker. 这是因为每个Document worker只能解析一次给定的模块。 There's no way for me to promise that I'll never use the module from a given URL again once I've thrown it away, thus there's no way for the ModuleMap to allow things to be collected. 我无法承诺,一旦我扔掉它,我将永远不再使用给定URL中的模块,因此ModuleMap无法允许收集内容。

And, indeed, reading through the Chromium source code, I don't see any calls to UnregisterModuleScript . 事实上,通过阅读Chromium源代码,我看不到对UnregisterModuleScript的任何调用。 It's entirely possible that this is not all the relevant code, but if it is, it stands to reason that any given instance of ModuleMap is going to hang on to its modules forever. 完全有可能这不是所有相关代码,但如果是这样,那么任何给定的ModuleMap实例都将永远挂在其模块上。

It seems like in theory I might be able to get the desired behavior from WebWorkers, since they have a different global scope. 从理论上讲,我似乎可以从WebWorkers获得所需的行为,因为它们具有不同的全局范围。 If anyone can tell me whether I'm barking up the right tree, that would be helpful. 如果有人能告诉我我是否正在吠叫正确的树,那将会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM