Share this Page URL

Chapter 4. Variables > Garbage Collection - Pg. 53

erence type that behaves like a primitive type or as a primitive type implemented with the internal efficiency of a reference type. Garbage Collection Reference types do not have a fixed size; indeed, some of them can become quite large. As we've already discussed, variables do not directly hold reference values. The value is stored at some other location, and the variables merely hold a reference to that lo- cation. Now we need to focus briefly on the actual storage of the value. Since strings, objects, and arrays do not have a fixed size, storage for them must be allocated dynamically, when the size is known. Every time a JavaScript program creates a string, array, or object, the interpreter must allocate memory to store that entity. Whenever memory is dynamically allocated like this, it must eventually be freed up for reuse, or the JavaScript interpreter will use up all the available memory on the system and crash. In languages like C and C++, memory must be freed manually. It is the programmer's responsibility to keep track of all the objects that are created and to destroy them (free- ing their memory) when they are no longer needed. This can be an onerous task and is often the source of bugs. Instead of requiring manual deallocation, JavaScript relies on a technique called gar- bage collection. The JavaScript interpreter is able to detect when an object will never again be used by the program. When it determines that an object is unreachable (i.e., there is no longer any way to refer to it using the variables in the program), it knows that the object is no longer needed and its memory can be reclaimed. Consider the following lines of code, for example: var s = "hello"; var u = s.toUpperCase( s = u; // Allocate memory for a string ); // Create a new string // Overwrite reference to original string After this code runs, the original string "hello" is no longer reachable -- there are no references to it in any variables in the program. The system detects this fact and frees up its storage space for reuse. Garbage collection is automatic and is invisible to the programmer. You can create all the garbage objects you want, and the system will clean up after you! You need to know only enough about garbage collection to trust that it works; you don't have to wonder about where all the old objects go. For those who aren't satisfied, however, Section 11.3, contains further details on the JavaScript garbage-collection process. Variables as Properties You may have noticed by now that there are a lot of similarities in JavaScript between variables and the properties of objects. They are both assigned the same way, they are Variables as Properties | 53