Serializing date on JSON.parse (v3)

Revision 3 of this benchmark created by Enzo on


Setup

function json_deserialize_helper(key,value) {
      if ( typeof value === 'string' ) {
        var regexp = /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.exec(value);
        if ( regexp ) {
          return new Date(value);
        }
      }
      return value;
    }
    function json_deserialize_helper2(key, value) {
        if (typeof value === 'string') {
            var regexp = /^\~(\d*)$/.exec(value);
            if (regexp)
                return new Date(Number(regexp[1]));
        }
        return value;
    }
    function json_serialize_helper(key, value) {
        if ( typeof value == 'string') {
            var test = /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.exec(value);
            if ( test )
                return '~' + new Date(test[0]).getTime();
        }
    
        return value;
    }
    
    var stringify = {test:new Date()};
    
    console.log( JSON.parse(JSON.stringify( stringify, json_serialize_helper ), json_deserialize_helper2).test.getDate() )
    console.log( JSON.parse(JSON.stringify( stringify ), json_deserialize_helper).test.getDate() )

Test runner

Ready to run.

Testing in
TestOps/sec
non serialized
JSON.parse(JSON.stringify( stringify ));
ready
serialized
JSON.parse(JSON.stringify( stringify ), json_deserialize_helper);
ready
serialized as timestamp
JSON.parse(JSON.stringify( stringify, json_serialize_helper ), json_deserialize_helper2);
ready

Revisions

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