The Benefits of NewtonScript

Garbage Collection

You never explicitly deallocate memory in NewtonScript. Instead, memory that is no longer referenced is available for reallocation.

Memory is allocated when you execute code that creates a nonimmediate (e.g., frame, array, or function). For instance, this code creates memory for two data structures (one array and one frame):

func()
begin
   local x := {j: 3, k: [1, 2, 3], l: 5};
end;
In addition, a number of functions allocate memory--for example, Clone and DeepClone.

Consider the following code, which demonstrates garbage collection:

func()
begin
   local x := {a: 2, b: 3, c:[1, 2, 3]};
   local y := x.c;  // Both y and x.c point to the same array

   x.c := nil;     // only y points to the array
   y := 5;
   return;  // The array is no longer referenced.
            // As x and y are no longer present, 
            // the frame is not referenced, either.
end;
Garbage collection (in its current implementation) works by starting with all the accessible variables. It then follows those variables and any frames or arrays until it can go no further. This determines all memory objects that can be reached; any others are unreachable and are marked for reuse.

Garbage collection occurs on a periodic basis as memory is needed. You don't need to do anything; the process is automatic. There is a GC() call that initiates garbage collection, but it is unlikely that you will ever need to use it.


An online version of Programming for the Newton using Macintosh, 2nd ed. ©1996, 1994, Julie McKeehan and Neil Rhodes.

Last modified: 1 DEC 1996