Search code examples
javascriptgetter-setterjsperf

speed of setter functions not what expected


I am comparing the performance of two different types of setters as shown below:

var q={};
var z={};
(function(){
  var x=1;
  q.x=function(){
    return x;
  };
  q.x.set=function(val){
    x=val;
  };
})();
(function(){
  var x=1;
  z.x=function(){
    return x;
  };
  z.x_set=function(val){
    x=val;
  };
})();

The difference lies in where the setter is stored: q.x.set vs z.x_set. I expected the z variant to run faster since it requires one less table look-up. On the contrary the q variant is consistently faster. Any ideas why? Here is the jsperf: http://jsperf.com/hq7f3


Solution

  • Your experiment now has a few results from various browsers. Lets look at the results.

    So we expect z to be faster than q. But when we examine the results we see two different categories of result.

    1. Results are nearly identical, trending towards q being slightly faster.
    2. OR z is a significantly faster.

    What this tells me is that this is at the mercy of implementation details of various JS engines. Different JS engines use a ton of low level optimizations this change the timing characteristics of these very small atomic operations. Perhaps the q pattern triggers an optimization that z does not in some browsers. Or perhaps some browsers have an optimization for the z pattern that older browsers did not support. But given the lack of consistency, the why is very hard to answer.

    One thing that is clear form the results so far, is that on average z is faster than q. Sometimes q is faster, but when z is faster, it's a lot faster.

    chart!


    But practically, the difference is negligible. This is a tiny operation. Tiny changes in a tiny operation can lead to large changes form a percentage perspective, but very very small changes to the performance profile in a larger application. Personally, I think this is academically interesting, but of little actual consequence.