4.5. 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 location. Now we need to focus briefly on the actual storage of the value.
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 (freeing their memory) when they are no longer needed. This can be an onerous task and is often the source of bugs.
var s = "hello"; // Allocate memory for a string var u = s.toUpperCase( ); // Create a new string s = u; // 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.
Copyright © 2003 O'Reilly & Associates. All rights reserved.