Object / Installation descriptor descriptor performance in recent versions of Chrome / V8

Considering

var obj = {}; var _a = 1; obj._a = 1; obj.aGetter = function() { return _a; } obj.aSetter = function(val) { _a = val; } Object.defineProperty(obj, 'a', { enumerable: true, get: function () { return _a; }, set: function(val) { _a = val; } }); 

using getter / setter functions

 obj.aSetter(2); obj.aGetter(); 

will have some performance degradation for Chrome / V8 (~ 3x) compared to direct access to properties:

 obj._a = 2; obj._a; 

It's clear. And using the getter / setter handle

 obj.a = 2; obj.a; 

will result in ~ 30x performance degradation in Chrome (41 to the last) - almost as slow as Proxy . Although Firefox and older versions of Chrome use the getter / setter handle without significant performance degradation.

What is the specific performance issue with getter / setter in recent versions of Chrome / V8? Is this a known issue that can be controlled?

Measurements were performed using Benchmark.js (jsPerf engine). I cannot provide a link to the jsPerf test to visualize the difference, because jsPerf has been seriously corrupted by anti-DDoS measures, but I am sure that there are existing ones that can prove the point.

+5
javascript google-chrome v8
source share
1 answer

Changes in performance are relevant to this Chromium problem (loans go to @VyacheslavEgorov).

To avoid performance issues, use a prototype instead. This is one of the few reasons why singleton classes can 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(); 
+7
source share

All Articles