Fabulous Adventures In Coding
Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric.
UPDATE: This article was written in 2003. Since that time the JScript garbage collector has been completely rewritten so as to be more performant in general, to handle the larger working sets entailed by modern web applications that we had absolutely no idea were coming when we designed the JScript GC back in 1995, to be better at predicting when there is garbage that needs collecting, and to be better at handling circular references involving browser objects. I did not do any of that work; I haven't worked on the script team for almost a decade now. I do not know how the modern JScript GC works; I've had the architect describe the basics to me but I am not an expert on it. This article should be considered "for historical purposes only"; it does not reflect how JScript works today.
JScript and VBScript both are automatic storage languages. Unlike, say, C++, the script developer does not have to worry about explicitly allocating and freeing each chunk of memory used by the program. The internal device in the engine which takes care of this task for the developer is called the garbage collector.
Interestingly enough though, JScript and VBScript have completely different garbage collectors. Occasionally people ask me how the garbage collectors work and what the differences are.
JScript uses a nongenerational mark-and-sweep garbage collector. It works like this:
Actually it is a little more complex than that, as we must worry about details like "what if freeing an item causes a message loop to run, which handles an event, which calls back into the script, which runs code, which triggers another garbage collection?" But those are just implementation details. (Incidentally, every JScript engine running on the same thread shares a GC, which complicates the story even further.)
You'll note that I hand-waved a bit there when I said "every now and then..." Actually what we do is keep track of the number of strings, objects and array slots allocated. We check the current tallies at the beginning of each statement, and when the numbers exceed certain thresholds we trigger a collection.
The benefits of this approach are numerous, but the principle benefit is that circular references are not leaked unless the circular reference involves an object not owned by JScript.
However, there are some down sides as well. Performance is potentially not good on large-working-set applications -- if you have an app where there are lots of long-term things in memory and lots of short-term objects being created and destroyed then the GC will run often and will have to walk the same network of long-term objects over and over again. That's not fast.
The opposite problem is that perhaps a GC will not run when you want one to. If you say "blah = null" then the memory owned by blah will not be released until the GC releases it. If blah is the sole remaining reference to a huge array or network of objects, you might want it to go away as soon as possible. Now, you can force the JScript garbage collector to run with the CollectGarbage() method, but I don't recommend it. The whole point of JScript having a GC is that you don't need to worry about object lifetime. If you do worry about it then you're probably using the wrong tool for the job.
VBScript, on the other hand, has a much simpler stack-based garbage collector. Scavengers are added to a stack when they come into scope, removed when they go out of scope, and any time an object is discarded it is immediately freed.
You might wonder why we didn't put a mark-and-sweep GC into VBScript. There are two reasons. First, VBScript did not have classes until version 5, but JScript had objects from day one; VBScript did not need a complex GC because there was no way to get circular references in the first place! Second, VBScript is supposed to be like VB6 where possible, and VB6 does not have a mark-n-sweep collector either.
The VBScript approach pretty much has the opposite pros and cons. It is fast, simple and predictable, but circular references of VBScript objects are not broken until the engine itself is shut down.
The CLR GC is also mark-n-sweep but it is generational – the more collections an object survives, the less often it is checked for life. This dramatically improves performance for large-working-set applications. Of course, the CLR GC was designed for industrial-grade applications, the JScript GC was designed for simple little web pages.
What happens when you have a web page, ASP page or WSH script with both VBScript and JScript? JScript and VBScript know nothing about each others garbage collection semantics. A VBScript program which gets a reference to a JScript object just sees another COM object. The same for a VBScript object passed to JScript. A circular reference between VBScript and JScript objects would not be broken and the memory would leak (until the engines were shut down). A noncircular reference will be freed when the object in question goes out of scope in both language (and the JS GC runs.)
For Vista/IE 7 (jscript 5.7) we did improve the heuristics for the JScript garbage collector. For some applications, the performance improvement is dramatic.
Here's how it works:
The initial threshholds and items counted are the same, but for vars and slots, they double (up to a large maximum) each time a collection recovers less than 15% of the outstanding items. The collector thereby roughly sizes itself to an app's working set as it it grows.
When a collection recovers more than 85% of the items, the counts are reset to the starting default.
The threshhold on total bytes in the SysAllocString string space does not adapt - just the vars and slots.
To trim memeory usage once the app has reached steady-state, a collection is also triggered every 10 seconds. For the timer-triggered collections, the threshholds are not changed.
PingBack from http://outatime.wordpress.com/2007/03/12/garbage-collection-in-ie6/
Can you clarify what the thresholds control.
There seems to be a little difference (mainly around the GcValTrigger) between what you mention above and the MS KB Hotfix article which seems to reference this issue.
0x100 GcVarTrigger, Variables Allocated
0x1000 GcValTrigger, Literal Values Allocated
0x10000 GccbSysTrigger, String Bytes Allocated
From your comments above
0x100 variables/temps/etc allocated (Does this include literals? String literals?)
0x1000 array slots allocated (assuming this is GcValTrigger, hence my confusion)
0x10000 bytes of strings allocated
I think this clarification would be useful. For example, if I knew that it was the literal theshold which was constantly being hit due to my code structure, I could look at optimizing code by setting the literals up as constants outside of my critical path/loop
Unfortunately, some of the things you'd change to reduce the number of times you hit the GC thresholds (like reducing short term variables/objects) have other performance impacts (like scope lookup) so it seems like it's a bit of a balancing act - but all I'm saying is that it would be good to have accurate info before starting off down this path.
NOTE: I agree that JS developers really should not be trying to write code centered around GC performance especially due to the balancing act above, but the reality is that there are an ever increasing number of complex JS based web applications out there with IE 6 support requirements and it would be really beneficial to find out what impact code structure has - since it's the only factor under the developers control.
PingBack from http://www.ajaxgirl.com/2007/03/07/garbage-collection-in-ie6/
I have an array, and i need to do three operations on this,
1. Add elements (added as and when i get updates from database)
2. Do some Processing (Not hamper the array values, just iterate and use these values)
3. Since the work is done (These elements are used only once ) remove them. Basically free up the memory.
For this third point is it ok if i just do myArray=new Array(); Will this free up the memory used for the previous elements. Since Iam not sure abt this what iam doing is :
Please suggest which one is correct.
First, if your array is so large that you feel that for performance reasons, you need to manage the memory yourself, then you are using the wrong programming language. You should be using a language like C that lets you have fine-grained control over memory management. So my advice in this case is "don't worry about it". If JScript works for you for this problem then let JScript manage your memory.
Second, supposing that you still do wish to free up the memory for performance reasons, well, if it is a local variable then it will be collected when the local variable goes out of scope. So, don't worry about it. If it is a global variable then... why are you using a global variable to store huge amounts of memory that you are processing temporary data with??? Stop doing that, use a more modular design to put this processing into a helper function, and let the script engine GC deal with scavenging the locals when they go out of scope. So again, my advice is "let the script engine manage your memory".
If that still doesn't dissuade you: to let the GC know that an array is available for scavenging, all you need to do is remove the last live reference to the array. It doesn't matter what the former live reference refers to afterwards, just so long as it isn't the thing you're trying to free. You can set it to null, zero, "your mother", whatever you want. null seems like a reasonable choice.
Of course, getting rid of the last live reference STILL doesn't do a collection. You have to wait for the GC to run. If you need to force the GC to run, see point one. You are using the wrong language. If that still doesn't dissuade you, call the collectGarbage method.
Unfortunately when the JScript engine was being "tweaked" for the IE 7 release a statement limit bug was introduced. Starting with jscript.dll 220.127.116.1130 dated Oct 17, 2006, a code block is now limited to 32767 statements. It was easily reproduced by 2 MSVPs. See my comments at http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?query=bug&dg=microsoft.public.scripting.jscript&cat=en_us_d7935fc4-a2a7-4ca3-be64-b36165171379&lang=en&cr=us&pt=&catlist=&dglist=&ptlist=&exp=&sloc=en-us. The thread is called "Statement limit bug".
People are already aware of IE-JScript circular memory leak problem. Let me take some time and explain
I write a blog about JScript, which is Microsoft's implementation of the ECMAScript programming language. I know rather a lot about that.
Unless specifically otherwise noted, my comments are always about JScript, the Microsoft implementation of ECMAScript. They should not be construed to be about other third-party implementations which I have little experience with or knowledge of.
thanks for these tips.
I am writing a little page that is probably badly coded and probably leaves all manner of global arrays in memory which would probably explain why IE grinds to a halt when I introduce 200ish div elements on the page...
Ill give your tips a go Eric.
And read your article again when im feeling a little brighter :)
@ Bill Robertson: 6 to 10 times faster ECMAScript implementation in Firefox might mean that its script engine was designed with different objectives than JScript in IE, i.e. designed to work not only "for simple little web pages", but "for industrial-grade applications" as well :)