Garbage collection (Definition)

The mechanism by which deallocated strings and objects are cleared from memory.

Garbage collection happens in JavaScript, but you have very little control over when and how. Since you don't have pointers, you cannot identify items that need to be released and nor do you need to.

Garbage collection happens in a web browser implementation when the page is reloaded. Any objects, strings, functions and variables you were using are discarded and no longer available. If you want to keep them around, you need to put them somewhere else, possibly in a parent FRAMESET object or as member properties of the Navigator object although that's not very portable.

The old JavaScript context is completely destroyed and a new one is made from scratch. This means that each page owns a pool of memory from which its scripts allocate storage. The pool is flushed on a page by page basis. This may get a little more complicated when you have scripts running across frames, since some pools will get flushed and others won't - be careful that the topmost frame does not become a memory hog, as this is the only one you cannot purge without losing all the session state. You could store the state data in cookies or in a transitory page in a separate window and then fetch it back again after the frame-set is regenerated. However, this "solution" is a bit of a hack, and it's better to solve the problem at source rather than try to hide the consequences.

There are many garbage collection algorithms, some better than others, but since you have no control over garbage collection, there is little point in investigating it, other than to influence the strategy you might use for creating and destroying objects. Some techniques may yield better performance in certain browsers due to the garbage collection algorithm the browser uses. Since the browser implementers tend to change this from time to time, there is no guarantee that a technique you deploy now will be optimal for the next version of the same browser.

However, you should try to avoid creating and destroying large numbers of strings and objects, since this seems to lead to memory leakage on most platforms. MSIE version 4 on Windows is particularly prone to this and it's not hard to develop animation loops that consume 50K of memory on each cycle. Virtually any elimination of String construction/destruction is worthwhile in cyclic situations. Indeed, you might find that innerText properties are a better place to store textual content than strings if things become extreme.

See also:delete, Execution environment, Memory leak, Memory management, Object(), Option(), Reference counting, Variable

Cross-references:

Wrox Instant JavaScript - page - 29