Is there any way to force the Javascript Garbage C

2020-08-09 09:45发布

问题:

In internet explorer we can force the Javascript garbage collection to execute with this method: CollectGarbage();

That method is undefined on Firefox. Do you know if there is some kind of equivalent?

Thanks.

回答1:

(Not just limiting this answer to WebKit-based browsers...)

  • Chrome: if you launch it from a command line/terminal with --js-flags="--expose-gc", then it provides window.gc().
  • Firefox I think requires clicking the "Free memory" buttons in about:memory.
  • Opera has window.opera.collect().
  • Edge has window.CollectGarbage().
  • Safari, unknown.

Note that you shouldn't be manually running the GC. I've only posted this because it's useful for development testing.



回答2:

I've been just trying to force GC and it seems that regardless of the actual browser relatively good way of doing so is to run following piece of code:

  function gc(max) {
    var arr = [];
    for (var i = 0; i < max; i++) {
      arr.push(i);
    }
    return arr.length;
  }
  for (var i = 0; ; i++) {
    // repeat until you have enough:
    gc(Math.pow(2, i));
  }

Of course, one issue is to know when to stop calling gc(...): for that one needs some external way to detect the GC is successfully over. In my case I was using embedded WebView and I could really check before forcing next round with bigger array.



回答3:

I'm not sure if this is not off topic but there is add-on for firefox called FreeMemory (https://addons.mozilla.org/en-US/firefox/addon/freememory/) to run garbage or cycle collection without visiting about:memory pane, with configurable timer. I believe there are alternatives for other browsers out there.



回答4:

Visit about:memory.

From page's documentation on MDN:

about:memory is a special page within Firefox that lets you view, save, 
load, and diff detailed measurements of Firefox's memory usage. It also 
lets you do other memory-related operations like trigger GC and CC