Negligible performance penalty for calling a function vs. accessing a property.

In the last post, I offered this little object as a way of encapsulating a get() / set() pair and their backing variable.

function Variable(initialValue) {
  'use strict';
  var value = initialValue;
  this.set = function(newValue) {
    value = newValue;
  this.get = function() {
    return value;

I got to wondering whether the extra level of indirection — hiding the variable behind get() and set() — would incur a performance penalty, so I created the following test. It tries each method, plus a baseline of doing nothing, 10 million times.

var myModule = (function() {
  'use strict';

  return {  
    myVariable: new Variable(0),
    myProperty: 0

function doTest(title, func) {  
  var count;
  var startTime = new Date().getTime();
  for (count=0; count<10000000; ++count) {
  var endTime = new Date().getTime();
  console.log(title +': ' + (endTime - startTime) + ' milliseconds');

doTest('Doing nothing', function() {});

doTest('With ordinary property', function () {
  myModule.myProperty = myModule.myProperty+1;

doTest('With fancy Variable', function() {

The results surprised me. On Chrome, using the getter and setter functions actually performed slightly better than accessing a variable directly. Internet Explorer 11 and Edge each showed a very slight performance degradation for the functions, but not enough to worry about: only a difference of 100 to 150 milliseconds for 10 million iterations. And yes, the chart is correct where it shows Edge performing an order of magnitude worse than doggy old IE.

The bottom line is that in all three browsers you may use the Variable object without worrying about performance problems.

Do-Nothing Baseline Ordinary Property Fancy Variable
Chrome 61 19 ms 71 ms 68 ms
IE 11 150 ms 141 ms 247 ms
Edge 1476 ms 1563 ms 1717 ms

One comment

  1. That was a really great test of performance! Thank you for showing us that efficiency won’t be thrown away for more DRYness.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.