Proposal: add an option to omit prototype of objects created by JSON.parse()

Michał Wadas michalwadas at gmail.com
Wed Sep 28 16:04:22 UTC 2016


Have you ever encountered performance issue because of copying object on
deserialization?

https://gist.github.com/Ginden/381448a17f50c7669b9a3693742e3a3d For me
results are:

Simple JSON.parse, 100000 iterations: 39.594999999997526ms
JSON.parse with copy, 100000 iterations: 184.5699999999997ms
JSON.parse with __proto__ change, 100000 iterations: 89.75500000000102ms



On Wed, Sep 28, 2016 at 5:49 PM, 段垚 <duanyao at ustc.edu> wrote:

> 在 2016/9/28 22:59, Danielle McLean 写道:
>
> From: 段垚 (mailto:duanyao at ustc.edu)
>> Date: 28 September 2016 at 16:36:52
>>
>> [I]mplementors warn that mutating prototype causes "performance
>>> hazards".
>>>
>> You don't actually need to mutate any prototypes to get prototypeless
>> objects out of `JSON.parse` - the reviver function is allowed to
>> return a new object instead, so you can create a fresh one with the
>> correct prototype. For example:
>>
>> ```js
>> JSON.parse(string, function(k, v) {
>>    if (v && typeof v === 'object' && !Array.isArray(v)) {
>>      return Object.assign(Object.create(null), v);
>>    }
>>    return v;
>> });
>> ```
>>
>
> Yes, but creating a copy also has performance penalty. This proposal is
> made for performance.
>
> How about adding an option to omit prototype of objects created by
>>> JSON.parse()?
>>>
>>> JSON.parse(str, { noPrototype: true });
>>>
>> While you can achieve the appropriate result already without extra
>> language support, I think this particular situation is common enough
>> that such an option might be a good idea.
>>
>> How would you expect this new parameter to interact with the existing
>> second parameter to `JSON.parse`, the reviver function? I'd suggest
>> that the cleanest way to add the options would be for the second
>> parameter to be either an object or function, like this:
>>
>> ```js
>> JSON.parse(str, someFunc);
>> // equivalent to
>> JSON.parse(str, {reviver: someFunc});
>> ```
>>
> Looks reasonable.
>
> Maybe we can simply add another method, say `JSON.parseWithoutPrototype()`.
> This makes feature detection easier.
>
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160928/e2a19350/attachment.html>


More information about the es-discuss mailing list