Finding the memory usage of JavaScript objects

Advanced JavaScript application features such as caches and undo buffers need to know the memory consumption of objects in order to function effectively. While JavaScript does not include a mechanism to find the exact memory usage of an object, sizeof.js provides a function that determines the approximate amount of memory used.

Download sizeof.js

Download one of the files below and upload it to your web server.

File Size Description
sizeof.js 1,886 bytes Full version, with comments
sizeof.compressed.js 762 bytes Compressed version

Link to the file using a script element in the head of your page:

1
<script type="text/javascript" src="sizeof.js"></script>

Using sizeof.js

The sizeof function takes an object as a parameter and returns its approximate size in bytes. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// define an object
var object =
    {
      'boolean' : true,
      'number'  : 1,
      'string'  : 'a',
      'array'   : [1, 2, 3]
    };

// determine the size of the object
var size = sizeof(object);

The sizeof function can handle objects that contain multiple references to other objects and recursive references.

Where now?

Found this useful? Share it:

Also in JavaScript: