Monday, December 9, 2013

Using the Chrome DevTools Heap Profiler to Explore Simple Javascript Objects

This is a short note demonstrating one use of the Heap Profile Snapshot capability of the Chrome browser.

In the table below are two examples.

In the first example, an object is created by calling a function that creates an object literal, with the object having two functions, and nothing further is done. The screenshot from the Heap Snapshot shows some internal information about the function. In particular, it shows how both functions getA and setA reference the same "context" that stores the variable myA. I believe that myA could also be referred to as a "closured variable", as Addy Osmani refers to in his section on the Singleton Pattern in his Learning JavaScript Design Patterns.

The second example is the same as the first, except there is one additional line where the setA method is called that modifies the local myA variable. Of course, since the context is shared, getA "sees" the new value as well.

Example 1. Create an object that has methods via an object literal

  function makeObjectLiteralWithFunctions(myA) {        
        return {  getA:function() {return myA;},
                  setA:function(newA) {myA = newA;}
                };       
      }
      
   var objectWithFunctions = makeObjectLiteralWithFunctions("theValue");
What the Heap Profile Snapshot in Chrome DevTools shows.

The functions getA and setA both share the same variable context.
Example 2. Create an object that has methods via an object literal, and call the method that sets the internal variable.

  function makeObjectLiteralWithFunctions(myA) {        
        return {  getA:function() {return myA;},
                  setA:function(newA) {myA = newA;}
                };       
      }
      
  var objectWithFunctions = makeObjectLiteralWithFunctions("theValue");

  objectWithFunctions.setA("new value");

What the Heap Profile Snapshot in Chrome DevTools shows.

Of course, the variable myA has value "new value" in the context shared by the two functions getA and setA, but I think it's instructive to confirm it with the Heap Profiler here.

No comments:

Post a Comment