JavaScript: Using Closure Space to Create Real Private Members

art13_closurespace_teaser_EN

I recently developed Angular Cloud Data Connector, which enables Angular developers to use cloud data, specifically Azure mobile service, using web standards like indexed DB. I was trying to create a way for JavaScript developers to embed private members into an object. My technique for this specific case is to use what I call “closure space”. In this tutorial, I want to share with you how to use this for your own projects and how performance and memory are impacted for the major browsers.
But before diving into it, let me share why you may need private members, as well as an alternate way to “simulate” private members.

Why Use Private Members?

When you create an object using JavaScript, you can define value members. If you want to control read/write access on them, you need accessors that can be defined like this:

1
2
3
4
5
6
7
8
9
10
11
var entity = {};
 
entity._property = "hello world";
Object.defineProperty(entity, "property", {
    get: function () { return this._property; },
    set: function (value) {
        this._property = value;
    },
    enumerable: true,
    configurable: true
});

Doing this, you have full control over read and write operations. The problem is that the _property member is still accessible and can be modified directly.

This is exactly why you need a more robust way to define private members that can only be accessed by object’s functions.

Using Closure Space

The solution is to use closure space. This memory space is built for you by the browser each time an inner function has access to variables from the scope of an outer function. This can be tricky sometimes, but for our topic this is a perfect solution.

So let’s alter the previous code to use this feature:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var createProperty = function (obj, prop, currentValue) {
    Object.defineProperty(obj, prop, {
        get: function () { return currentValue; },
        set: function (value) {
            currentValue = value;
        },
        enumerable: true,
        configurable: true
    });
}
 
var entity = {};
 
var myVar = "hello world";
createProperty(entity, "property", myVar);

In this example, the createProperty function has a currentValue variable that get and set functions can see. This variable is going to be saved in the closure space of get and set functions. Only these two functions can now see and update the currentValue variable! Mission accomplished!

The only caveat we have here is that the source value (myVar) is still accessible. So here comes another version for even more robust protection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var createProperty = function (obj, prop) {
    var currentValue = obj[prop];
    Object.defineProperty(obj, prop, {
        get: function () { return currentValue; },
        set: function (value) {
            currentValue = value;
        },
        enumerable: true,
        configurable: true
    });
}
 
var entity = {
    property: "hello world"
};
 
createProperty(entity, "property");

Using this method, even the source value is destructed. So mission fully accomplished!

Performance Consideration

Let’s now have a look at performance.

Obviously, closure spaces or even properties are slower and more expensive than just a plain variable. That’s why this article focuses more on the difference between regular way and closure space technique.

To confirm the closure space approach is not too expensive compared to the standard way, I wrote this little benchmark:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <title></title>
  </head>
  <style>
  html {
  font-family: "Helvetica Neue", Helvetica;
  }
  </style>
  <body>
  <div id="results">Computing...</div>
  <script>
  var results = document.getElementById("results");
  var sampleSize = 1000000;
  var opCounts = 1000000;
 
 var entities = [];
 
 setTimeout(function () {
  // Creating entities
  for (var index = 0; index < sampleSize; index++) {
  entities.push({
  property: "hello world (" + index + ")"
  });
  }
 
 // Random reads
  var start = new Date().getTime();
  for (index = 0; index < opCounts; index++) {
  var position = Math.floor(Math.random() * entities.length);
  var temp = entities[position].property;
  }
  var end = new Date().getTime();
 
 results.innerHTML = "<strong>Results:</strong><br>Using member access: <strong>" + (end - start) + "</strong> ms";
  }, 0);
 
 setTimeout(function () {
  // Closure space =======================================
  var createProperty = function (obj, prop, currentValue) {
  Object.defineProperty(obj, prop, {
  get: function () { return currentValue; },
  set: function (value) {
  currentValue = value;
  },
  enumerable: true,
  configurable: true
  });
  }
  // Adding property and using closure space to save private value
  for (var index = 0; index < sampleSize; index++) {
  var entity = entities[index];
 
 var currentValue = entity.property;
  createProperty(entity, "property", currentValue);
  }
 
 // Random reads
  var start = new Date().getTime();
  for (index = 0; index < opCounts; index++) {
  var position = Math.floor(Math.random() * entities.length);
  var temp = entities[position].property;
  }
  var end = new Date().getTime();
 
 results.innerHTML += "<br>Using closure space: <strong>" + (end - start) + "</strong> ms";
  }, 0);
 
 setTimeout(function () {
  // Using local member =======================================
  // Adding property and using local member to save private value
  for (var index = 0; index < sampleSize; index++) {
  var entity = entities[index];
 
 entity._property = entity.property;
  Object.defineProperty(entity, "property", {
  get: function () { return this._property; },
  set: function (value) {
  this._property = value;
  },
  enumerable: true,
  configurable: true
  });
  }
 
 // Random reads
  var start = new Date().getTime();
  for (index = 0; index < opCounts; index++) {
  var position = Math.floor(Math.random() * entities.length);
  var temp = entities[position].property;
  }
  var end = new Date().getTime();
 
 results.innerHTML += "<br>Using local member: <strong>" + (end - start) + "</strong> ms";
  }, 0);
 
 </script>
  </body>
  </html>

I create 1 million objects, all with a property member. Then I do three tests:

  • Do 1 million random accesses to the property
  • Do 1 million random accesses to the “closure space” version
  • Do 1 million random accesses to the regular get/set version

Here are a table and a chart about the result:


We can see that the closure space version is always faster than the regular version and depending on the browser, it can be a really impressive optimization.

Chrome performance is less than I expected. There may be a bug so to be sure, I contacted Google’s team to figure out what’s happening here. Also if you want to test how this performs in Microsoft Edge – Microsoft’s new browser that will ship default with Windows 10 – you can download it here.

However, if we look closely we can find that using closure space or even a property can be ten times slower than direct access to a member. So be warned and use it wisely.

Memory Footprint

We also have to check if this technique does not consume too much memory. To benchmark memory I wrote these three little pieces of code:

Reference Code

1
2
3
4
5
6
7
8
9
10
var sampleSize = 1000000;
 
var entities = [];
 
// Creating entities
for (var index = 0; index < sampleSize; index++) {
    entities.push({
        property: "hello world (" + index + ")"
    });
}

Regular Way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var sampleSize = 1000000;
 
var entities = [];
 
// Adding property and using local member to save private value
for (var index = 0; index < sampleSize; index++) {
    var entity = {};
 
    entity._property = "hello world (" + index + ")";
    Object.defineProperty(entity, "property", {
        get: function () { return this._property; },
        set: function (value) {
            this._property = value;
        },
        enumerable: true,
        configurable: true
    });
 
    entities.push(entity);
}

Closure Space Version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var sampleSize = 1000000;
 
var entities = [];
 
var createProperty = function (obj, prop, currentValue) {
    Object.defineProperty(obj, prop, {
        get: function () { return currentValue; },
        set: function (value) {
            currentValue = value;
        },
        enumerable: true,
        configurable: true
    });
}
 
// Adding property and using closure space to save private value
for (var index = 0; index < sampleSize; index++) {
    var entity = {};
 
    var currentValue = "hello world (" + index + ")";
    createProperty(entity, "property", currentValue);
 
    entities.push(entity);

Then I ran all these three codes and I launched the embedded memory profiler (Example here using F12 tools):

Here are the results I got on my computer:

Between closure space and regular way, only Chrome has slightly better results for closure space version. IE11 and Firefox use a bit more memory but the browsers are relatively comparable – users probably won’t notice a difference across the modern browsers.

More Hands-On with JavaScript

It might surprise you a bit, but Microsoft has a bunch of free learning on many open source JavaScript topics and we’re on a mission to create a lot more with Microsoft Edge coming. Check out my own:

Or our team’s learning series:

And some free tools: Visual Studio Community, Azure Trial, and cross-browser testing tools for Mac, Linux, or Windows.

Conclusion

As you can see, closure space properties can be a great way to create really private data. You may have to deal with a small increase in memory consumption but from my point of view this is fairly reasonable (and at that price you can have a great performance improvement over using the regular way).

Feel free to ping me on twitter if you want to discuss about this article: @deltakosh

And by the way if you want to try it by yourself, please find all the code used here. There’s a good “how-to” on Azure Mobile Services here.

This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ modern.IE.

(dpe)

David Catuhe

David Catuhe is a Principal Program Manager at Microsoft focusing on web development. He is author of the babylon.js framework for building 3D games with HTML5 and WebGL.  Read his blog on MSDN or follow him @deltakosh on Twitter.