Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to force the Javascript Garbage Collector in webkit based browsers?

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.

like image 939
xus Avatar asked Apr 19 '12 11:04

xus


People also ask

Is garbage collection automatically in JavaScript?

Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it.

What is garbage collection and how is it performed in JavaScript apps?

When it comes to programming, Garbage Collection means cleaning the memory spaces which don't contain useful data and then reallocating those cleared memory to some other data which is both active and useful. That is the basic process of Garbage Collection in pretty much all the programming languages in the world.

Can we force garbage collector to run in C#?

You can force garbage collection either to all the three generations or to a specific generation using the GC. Collect() method. The GC. Collect() method is overloaded -- you can call it without any parameters or even by passing the generation number you would like to the garbage collector to collect.


2 Answers

(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.

like image 88
ZachB Avatar answered Sep 23 '22 01:09

ZachB


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.

like image 41
Jaroslav Tulach Avatar answered Sep 25 '22 01:09

Jaroslav Tulach