Why is mutating the [[prototype]] of an object bad for performance?

后端 未结 4 2043
礼貌的吻别
礼貌的吻别 2020-11-22 14:36

From the MDN docs for the standard setPrototypeOf function as well as the non-standard __proto__ property:

Mutating the [[Prototype]] of an

4条回答
  •  天涯浪人
    2020-11-22 15:11

    Here is a benchmark using node v6.11.1

    NormalClass: A normal class, with the prototype non edited

    PrototypeEdited: A class with the prototype edited (the test() function is added)

    PrototypeReference: A class with the added prototype function test() who referer to an external variable

    Results :

    NormalClass x 71,743,432 ops/sec ±2.28% (75 runs sampled)
    PrototypeEdited x 73,433,637 ops/sec ±1.44% (75 runs sampled)
    PrototypeReference x 71,337,583 ops/sec ±1.91% (74 runs sampled)
    

    As you can see, the prototype edited class is a way faster than the normal class. The prototype who has a variable which refer to an external one is the slowest, but that's an interesting way to edit prototypes with already instantied variable

    Source :

    const Benchmark = require('benchmark')
    class NormalClass {
      constructor () {
        this.cat = 0
      }
      test () {
        this.cat = 1
      }
    }
    class PrototypeEdited {
      constructor () {
        this.cat = 0
      }
    }
    PrototypeEdited.prototype.test = function () {
      this.cat = 0
    }
    
    class PrototypeReference {
      constructor () {
        this.cat = 0
      }
    }
    var catRef = 5
    PrototypeReference.prototype.test = function () {
      this.cat = catRef
    }
    function normalClass () {
      var tmp = new NormalClass()
      tmp.test()
    }
    function prototypeEdited () {
      var tmp = new PrototypeEdited()
      tmp.test()
    }
    function prototypeReference () {
      var tmp = new PrototypeReference()
      tmp.test()
    }
    var suite = new Benchmark.Suite()
    suite.add('NormalClass', normalClass)
    .add('PrototypeEdited', prototypeEdited)
    .add('PrototypeReference', prototypeReference)
    .on('cycle', function (event) {
      console.log(String(event.target))
    })
    .run()
    

提交回复
热议问题