toJSON vs stringify replacer (v2)

Revision 2 of this benchmark created by Alexandre Barreira on


Description

Comparing the performance of using prototype.toJSON vs an analogous replacer function used in the JSON.stringify method.

Setup

var MyClass = function MyClass() {
      this.property = 'something';
    }
    
    var MyClassToJSON = function MyClassToJSON() {
      this.property = 'something';
    }
    
    MyClassToJSON.prototype.toJSON = function toJSON() {
      this.property = 'else';
      return this;
    }
    
    function replacer(prop, value) {
      if(value instanceof MyClass) {
        value.property = 'else';
      }
      return value;
    }
    
    var arrReplacer = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
    
    var my = new MyClass();
    var my2json = new MyClassToJSON();
    
    var temp1 = { 
      one: 1,
      two: "two",
      three: true,
      four: null,
      five: new MyClassToJSON(),
      six: new MyClassToJSON(),
      seven: new MyClassToJSON(),
      eight: new MyClassToJSON(),
      nine: new MyClassToJSON(),
      ten: new MyClassToJSON(),
    };
    
    var temp2 = { 
      one: 1,
      two: "two",
      three: true,
      four: null,
      five: new MyClass(),
      six: new MyClass(),
      seven: new MyClass(),
      eight: new MyClass(),
      nine: new MyClass(),
      ten: new MyClass(),
    };

Test runner

Ready to run.

Testing in
TestOps/sec
w/ toJSON
JSON.stringify(temp1);
ready
w/ replacer
JSON.stringify(temp2, replacer);
ready
w/ neither
JSON.stringify(temp2);
ready
w/ array replacer
JSON.stringify(temp2, arrReplacer);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Nathan on
  • Revision 2: published by Alexandre Barreira on