Using JSON.stringify and JSON.parse to serialize and deserialize objects has subtle problems such as date objects being serialized as strings and then coming out on the other side as strings rather than date objects. I’ve tried using postMessage instead which has the benefit of producing 1:1 results, but I’m worried about other handlers eaves dropping on the messages. I’ve considered writing my own serializer/deserializer, but would prefer native browser capabilities.
Is there a way to use postMessage like a serializer, without having to worry about eavesdropping?
NOTE: I don’t care about eavesdropping using dev tools. My app is loading plugin like modules and I want to make sure those aren’t able to eavesdrop on messages that are for other modules.
You can supply a custom JSON parser/stringifier to
JSON.stringifyandJSON.parse:In addition to the custom reviver, you can also define a
toJSONmethod on the object which is going to be serialized. This method receives one argument: the key’s name indexes in arrays, property names in objects, if applicable.Here’s a JSPerf comparison of native parsing vs parsing with a reviver: http://jsperf.com/json-reviver. It shows that a custom reviver which does nothing special is two times slower, and that a reviver with expensive functionality is significantly slower.
However, when the last method is compared to a weaker method using native JSON and “manual conversion”, then the differences seems to be neglected.
Note: Only a single value is benchmarked. Make sure to create a custom benchmark for your own (specific) case, because it’s impossible to create one benchmark which represents every possible case.
I have created a JSPerf test case which checks the impact of
.toJSON. To isolate noise, I’ve created a test case based on theDateobject. A custom function with several function calls is just two times slower than a nativeDate.prototype.toJSON.