问题
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. 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.
The reason why seems to be related to something called the ModuleMap
. Here's a screenshot from a memory snapshot I took after all scripts were no longer in use.
As you can see, the Window object is is providing a retaining path down to these modules. 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.
回答1:
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. 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.
And, indeed, reading through the Chromium source code, I don't see any calls to 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.
It seems like in theory I might be able to get the desired behavior from WebWorkers, since they have a different global scope. If anyone can tell me whether I'm barking up the right tree, that would be helpful.
来源:https://stackoverflow.com/questions/50284661/garbage-collect-unused-modules