Skip to content

Instantly share code, notes, and snippets.

@davidmurdoch
Forked from justinbmeyer/jsmem.md
Created January 30, 2013 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidmurdoch/4674779 to your computer and use it in GitHub Desktop.
Save davidmurdoch/4674779 to your computer and use it in GitHub Desktop.

JavaScript Code

var str = "hi";

Memory allocation:

Address Value Description
...... ...
0x1001 call object Start of a call object's memory
0x1002 0x00af Reference to invoked function
0x1003 1 Number of references in this call object
0x1004 str Name of variable (in practice would not be in a single address)
0x1005 0x1001 Memory address of "hi"
...... ...
0x2001 string type identifier
0x2002 2 number of bytes
0x2003 h byte of first character
0x2004 i byte of second character

Explanation

When JS runs: var str = "hi"; by calling some function, it first hoists all variable declarations and creates a spot in memory for the variable. This might leave memory something like:

Address Value Description
...... ...
0x1001 call object Start of a call object's memory
0x1002 0x00af Reference to invoked function
0x1003 1 Number of references in this call object
0x1004 str Name of variable
0x1005 empty
...... ...

In practice, the name of the variable, str, would not be held in a single memory address. Also, the variable names and locations would not be stored in a fixed-memory array (possibly in a hash-table).

Next, the string "hi" would be created in memory like:

Address Value Description
...... ...
0x2001 string type identifier
0x2002 2 number of bytes
0x2003 h byte of first character
0x2004 i byte of second character

Finally, the pointer address of str would be set to the memory address of "hi" (0x2001), leaving memory as indicated at the top of the page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment