I want to trigger JavaScript garbage collection. Is it possible? Why would I want to, or not want to, do this?
-
2What's driving you to do this? – Michael Petrotta Nov 07 '11 at 05:09
-
Not in a cross-platform way, AFAIK. It's also unlikely the JS engine isn't already doing what it can in that regard, although GC efficacy is implementation-specific. I don't know why you'd want to. – Dave Newton Nov 07 '11 at 05:12
-
7No. [comment limit] – RobG Nov 07 '11 at 05:13
-
2Hi,actually in my application,huge data are coming through ajax call on every 20 second.Due to heave data browser get crashed after few minutes.So that i want to clear browser's memory to avoid the failure of browser. – Abhinav Nov 07 '11 at 05:29
-
2The problem you should be solving is that of your browser receiving so much data in the first place. – BoltClock Nov 07 '11 at 07:43
-
8This comment from BoltClock is very useless. In a simple "my company looks like this"-homepage this is in some case true, but when you develope a "software" which for example collects sensor stats live in a highstock chart, there is nothing wrong to have "huge" data. – prdatur Mar 07 '15 at 17:14
-
1avoid repeating var and new (move them to closure scope). Search for other tricks like this. It can improve the performance hundreds of times. – Sohail Si Jun 14 '16 at 13:27
-
Check the dgc function of https://jailbreak.me/ – XMB5 Sep 12 '18 at 00:19
-
3A very good reason to trigger a GC is right before starting certain kinds of animation. We don't want to see hesitation during an animation. – David Spector Jan 26 '19 at 23:20
-
For debugging, in Firefox you can open `about:memory`, and click the buttons under the "Free Memory" section. Or inspect the button events, and use what you find there: `Cu.forceGC();`, `window.windowUtils.cycleCollect();`, `gMgr.minimizeMemoryUsage(()=>0);` – biziclop Oct 05 '22 at 08:36
9 Answers
I went out on a small journey to seek an answer to one of your questions: Is it possible?
People all over town are saying that deleting the references will do the trick. Some people say that wiping the object is an extra guarantee (example). So I wrote a script that will try every trick in the book, and I was astonished to see that in Chrome (22.0.1229.79) and IE (9.0.8112.16421), garbage collection doesn't even seem to work. Firefox (15.0.1) managed without any major drawbacks apart from one (see case 4f down below).
In pseudo-code, the test goes something like this.
Create a container, an array, that will hold objects of some sort. We'll call this container
Bertil
here on.Each and every object therein, as an element in Bertil, shall have his own array-container declared as a property. This array will hold a whole lot of bytes. We'll call any one of Bertil's elements, the object,
Joshua
. Each Joshua's byte array will be calledSmith
.Here's a mind map for you to lean back on:
Bertil
[Array of objects] ->Joshua
[Object] ->Smith
[Array of bytes] -> Unnamed [Bytes].When we've made a mess out of our available memory, hang around for a sec or two and then execute any one of the following "destruction algorithms":
4a. Throw a delete operand on the main object container, Bertil.
4b. Throw a delete operand on each and every object in that container, kill every Joshua alive.
4c. Throw a delete operand on each and every array of bytes, the Smiths.
4d. Assign NULL to every Joshua.
4e. Assign UNDEFINED to every Joshua.
4f. Manually delete each and every byte that any Joshua holds.
4g. Do all of the above in a working order.
So what happened? In case 4a and 4b, no browser's garbage collector (GC) kicked in. In case 4c to 4e, Firefox did kick in and displayed some proof of concept. Memory was reclaimed shortly within the minute. With current hardcoded default values on some of the variables used as test configuration, case 4f and 4e caused Chrome to hang, so I can't draw any conclusions there. You are free to do your own testing with your own variables, links will be posted soon. IE survived case 4f and 4e but his GC was dead as usual. Unexpectedly, Firefox survived but didn't pass 4f. Firefox survived and passed 4g.
In all of the cases when a browser's GC failed to kick in, waiting around for at least 10 minutes didn't solve the problem. And reloading the entire page caused the memory footprint to double.
My conclusion is that I must have made a horrible error in the code or the answer to your question is: No we can't trigger the GC. Whenever we try to do so we will be punished severely and we should stick our heads in the sand. Please I encourage you to go ahead, try these test cases on your own. Have a look in the code were comment on the details. Also, download the page and rewrite the script and see if you can trigger the GC in a more proper way. I sure failed and I can't for the life of me believe that Chrome and IE doesn't have a working garbage collector.
http://martinandersson.com/dev/gc_test/?case=1
http://martinandersson.com/dev/gc_test/?case=2
http://martinandersson.com/dev/gc_test/?case=3
http://martinandersson.com/dev/gc_test/?case=4
http://martinandersson.com/dev/gc_test/?case=5

- 20,799
- 66
- 75
- 101

- 18,072
- 9
- 87
- 115
-
2I've also noticed that deleting lots of objects in V8 engine (Chrome) is a bad idea. It's simply very slow and assigning to null is much faster. – jjrv Oct 20 '12 at 08:43
-
3You said: "deleting lots of objects". Might be good to know for you that you can't delete an object in JS (nor functions or variables), only object properties and array elements. Assigning null (or undefined?) to every object reference once we're done with em should be all we need to do. IN THEORY. But as my little research demonstrated I failed utterly hard in firing up the GC in Chrome and IE. Basically, there should be hard to achieve a memory leak in managed code with its own garbage collector, for me, it was the opposite. – Martin Andersson Oct 20 '12 at 23:17
-
2+1, possibly the BEST answer I've ever read on SO. Entertaining (but not too) way written, exactly to the spot. I'm building really dynamic data management - that possibly will use browser as a data-bridge from Google Spreadsheets and alike. So "you got too big data" will be my issue as well... – Kallex Feb 07 '14 at 14:22
-
2@MartinAndersson I went and ran your tests. Then discovered (also mentioned in the answers below), that IE honors the explicit call to "CollectGarbage()" (I added it to your case 2 pattern just by testing it out - didn't test thoroughly). While it's "not recommended", it frees the memory while waiting didn't free anything... – Kallex Feb 07 '14 at 14:56
-
1a lot of developers have problem with memory , i think google and firefox should allow manual run of their garbage collectors , i tried waiting in my script not worked , chrome GC come in action when script finish on waiting it not start – user889030 Aug 15 '17 at 11:12
-
-
@Pacerier Maybe now, but it definitely should have been the accepted answer when it was relevant. I would like to see someone report on running these tests now. – WebWanderer Sep 18 '17 at 13:51
-
1I know this is an old post, but I would like to add some extra context here to others that stumble across this. Calling `delete` on anything in JS should be avoided unless absolutely needed. Why? Because it breaks JS engine optimization for that object for as long as it lives (at least for V8... I am not certain about other engines). You can see this real-time by using the profiler. If you call `delete` on a key, you will see in the profiler that the object will now be marked as "Deoptimized". Good reading: https://github.com/P0lip/v8-deoptimize-reasons – th317erd Jul 27 '22 at 19:36
You can trigger manually JavaScript garbage collector in IE and Opera, but it's not recommended, so better don't use it at all. I give commands more just for information purpose.
Internet Explorer:
window.CollectGarbage()
Opera 7+:
window.opera.collect()

- 516
- 4
- 11
Garbage collection runs automatically. How and when it runs and actually frees up unreferenced objects is entirely implementation specific.
If you want something to get freed, you just need to clear any references to it from your javascript. The garbage collector will then free it.
If you explain why you even think you need to do this or want to do this and show us the relevant code, we might be able to help explain what your alternatives are.

- 683,504
- 96
- 985
- 979
-
3Hi,actually in my application,huge data are coming through ajax call on every 20 second.Due to heavy data browser get crashed after few minutes.So that i want to clear browser's memory to avoid the failure of browser – Abhinav Nov 07 '11 at 05:43
-
@Abhinav - Show us the relevant code and we can advise. You can't call the garbage collector yourself. – jfriend00 Nov 07 '11 at 05:44
-
1Code is very simple,actually we generating dynamic graph through live data that is coming on every 20 second.Problem already explained. – Abhinav Nov 07 '11 at 05:50
-
1So to over come with this problem i want to clear browser after some time,so my query is ,is it possible to clear browser memory through script ] – Abhinav Nov 07 '11 at 05:51
-
5I've already answered you what can be done without seeing your code. You cannot invoke the garbage collector yourself. If you clear all references to this big data and allow some free cycles to the JS engine, the garbage collector will free it for you. I can only advise how to do that by seeing your specific code. – jfriend00 Nov 07 '11 at 05:57
-
@Abhinav - show the code for what you do with the data that comes in, and you'll probably get some advice on whether it's structured in a way that will hold on to memory. The only way to clear browser memory is what jfriend00's answer already says: free up any references to memory-hogging objects so that the garbage collector can run (and then hope that it runs soon since you can't actually make it run on cue). – nnnnnn Nov 07 '11 at 06:02
-
3@Abhinav - The other way to clear browser memory is to reload the page rather than just using ajax and staying on the same page - though that shouldn't be necessary if your code is structured properly to release references to data it is no longer using. – jfriend00 Nov 07 '11 at 06:16
-
The main reason I want to collect garbage manually is for testing code that uses WeakSets, Maps, and Refs, to be sure things are working correctly. It can be done in the JVM and is really useful for ensuring Weak Reference management is done correctly. – Yona Appletree Jun 23 '20 at 19:50
- Check your code for global variables. There may be data coming through an ajax call that is stored, and then referenced somewhere and you did not take this into account.
- As a solution, you should wrap huge data processing into an anonymous function call and use inside this call only local variables to prevent referencing the data in a global scope.
- Or you can assign to null all used global variables.
- Also check out this question. Take a look at the third example in the answer. Your huge data object may still be referenced by async call closure.
This answer suggests the following garbage collection request code for Gecko based browsers:
window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindowUtils)
.garbageCollect();

- 1
- 1

- 221
- 2
- 5
-
2According to MDN, the garbageCollect function "Will throw a DOM security error if called without UniversalXPConnect privileges in non-debug builds. Available to all callers in debug builds." May not be available in all modern browsers. Downvoted. – David Spector Jan 26 '19 at 23:27
Yes, you can trigger garbage collection by re-loading the page.
You might want to consider using a Factory Pattern to help re-use objects, which will greatly cut down on how many objects are created. Especially, if you are continuously creating objects that are the same.
If you need to read up on Factory Patterns then get yourself this book, "Pro Javascript Design Patterns" by Ross Harmes and Dustin Diaz and published by APress.

- 293
- 1
- 3
- 7
-
45
-
5I believe that this is *not* the intent of original question. Refreshing the page is obviously the way to wipe all, but it can't be a solution for long running SPAs with complex logic, where the GC work is accute. – GullerYA Oct 23 '15 at 12:14
-
@Trevor, Reloading the page is doing nongarbage collection too, not just garbage collection. Don't throw the baby out! – Pacerier Sep 18 '17 at 10:06
-
refreshing the page just doubles my ram memory footprint in IE11, so frustrating. I have to open a new window and close the old one to get the tab's memory released that was closed. Big issue is since the memory is so full i cant open another window – Coty Embry Oct 02 '20 at 17:03
Came across this question and decided to share with my recent findings. I've looked to see a proper handling of a WeakMap in Chrome and it's actually looks okay:
1) var wm = new WeakMap()
2) var d = document.createElement('div')
3) wm.set(d, {})
at this stage weak map holds the entry cause d is still referencing the element
4) d = null
at this stage nothing references the element and it's weakly referenced object, and indeed after a couple of minutes entry disappeared and garbage collected.
when did the same but appended the element to the DOM, it was not reclaimed, which is correct, removed from the DOM and still waiting for it to be collected :)

- 1,320
- 14
- 27
-
Re "and indeed after a couple of minutes entry disappeared and garbage collected" how did you verify that? – Pacerier Sep 18 '17 at 10:09
-
Well, it has been quite a while since then, but AFAIR, i've just inspected the memory graph in the DevTools (heap snapshot). – GullerYA Sep 27 '17 at 19:57
-
Eventually triggering a GC after a few minutes is useless in the common use case of triggering a GC before certain kinds of animation, to avoid hesitation in the animation. – David Spector Jan 26 '19 at 23:31
I was reading Trevor Prime's answer and it gave me a chuckle but then I realized he was on to something.
- Reloading the page does 'garbage-collect'.
- location.reload() or alternatives to refresh page.
- JSON.parse/stringify and localStorage.getItem/setItem for persistence of needed data.
- iframes as reloading pages for user experience.
All you need to do is run your code in an iframe and refresh the iframe page while saving useful information into localStorage. You'll have to make sure the iframe is on the same domain as main page to access its DOM.
You could do it without an iframe but user experience will no doubt suffer as the page will be visibly resetting.

- 11
- 2
-
1I doubt iframe reloading is gonna make a difference. You'd need to do a full top reload. – Pacerier Sep 18 '17 at 10:08
-
Reloading is useless in the common use case of animation. Animations should be possible anytime, not just on page load, which is visible to the user. – David Spector Jan 26 '19 at 23:32
If it is true that there is no way to trigger a GC, as implied by the other answers, then the solution would be for the appropriate browser standards group to add a new JavaScript function to window or document to do this. It is useful to allow the web page to trigger a GC at a time of its own choosing, so that animations and other high-priority operations (sound output?) will not be interrupted by a GC.
This might be another case of "we've always done it this way; don't rock the boat" syndrome.
ADDED:
MDN documents a function "Components.utils.schedulePreciseGC" that lets a page schedule a GC sometime in the future with a callback function that is called when the GC is complete. This may not exist in browsers other than Firefox; the documentation is unclear. This function might be usable prior to animations; it needs to be tested.

- 1,520
- 15
- 21