Primitive and Reference Values in Memory



Navigation Aids -- This Page        Navigation Aids -- This Topic        Navigation Aids -- This Site








Topic Terms

Primitive Values and Memory

The location (on the stack) of a variable with a primitive data type will contain the value of the initializing token (the data). This data is stored on the stack. Primitive values are all (except string) associated with a fixed size and therefore can be placed on the faster stack memory.

Each primitive data type has a fixed storage size. The floating point number has the largest requirement for storage. It takes 8-bytes to store the 64-bit float. Therefore, the stack is allocated in 8-byte clusters for each variable even though some variables don't need the full 8-bytes. The 8-byte allocation for each variable makes sense when you recall that JavaScript variables are untyped. A variable that is a float can be reinitialized as a integer which can be reinitialized as a boolean and so on. So, regardless of data type, the storage allocation on the stack for a variable will not change.

Reference Values and Memory

The location (on the stack) of a reference variable contains a pointer (address). This pointer points to where the object is stored on the heap. Three things happen when a reference type variable is initialized:

  1. The values used to initialize the reference are placed on the heap. The reference value (arrays, objects, functions) size will vary and therefore, should not be placed on the stack.
  2. The address of the location in the heap (step 1 above) is placed on the stack.
  3. The identifier of the var statement is associated with the address placed on the stack (step 2). The identifier is essentially a pointer into the heap.

The Deallocation of Variables

In JavaScript, we do not explicitly deallocate variable data (objects) for reference types. The interpreter is able to dynamically determine when a reference type is no longer needed. The interpreter can determine at any point in your code when previously legitimate objects will no longer be reference in subsequent code. At this point the data representing the reference type is destroyed (no longer exists on the heap). The process is called garbage collection. Strings, objects, functions and arrays all can go the way of the garbage collector.

String Data Type: Heap or Stack??

The primitive string data type does not have a fixed data size. The size of the data can vary from one string to another. In JavaScript, all other primitive data types have a fixed size based on there data type. The fixed sized primitive values are placed on the stack. The inconsistent sized reference values are placed on the heap. Where to put the string values? As with most languages and with JavaScript, the string values go on the heap because of the varying size.



Top            

Rx4AJAX        About Us | Topic Index | Contact Us | Privacy Policy | 2008 This Site Built By PPThompson