Object descriptor getter/setter performance in recent Chrome/V8 versions

前端 未结 1 1241
心在旅途
心在旅途 2020-11-29 13:01

Given

var obj = {};

var _a = 1;

obj._a = 1;

obj.aGetter = function() {
  return _a;
}

obj.aSetter = function(val) {
  _a = val;
}

Object.defineProperty(         


        
相关标签:
1条回答
  • 2020-11-29 13:40

    The changes in performance are relevant to this Chromium issue (credits go to @VyacheslavEgorov).

    To avoid performance issues, a prototype should be used instead. This is one of few reasons why singleton classes may be used to instantiate an object once.

    With ES5:

    var _a = 1;
    
    function Obj() {}
    
    Object.defineProperty(Obj.prototype, 'a', {
      enumerable: true,
      get: function () {
        return _a;  
      },
      set: function(val) {
        _a = val;
      }     
    });
    
    var obj = new Obj();
    // or
    var obj = Object.create(Obj.prototype);
    

    Or with ES6 syntactic sugar:

    class Obj {
      constructor() {
        this._a = 1;
      }
    
      get a() {
        return this._a;
      }
    
      set a(val) {
        this._a = val;
      }     
    }
    
    let obj = new Obj();
    
    0 讨论(0)
提交回复
热议问题