4 ms·
The runtime can't know whether it's parsing a plain old JSON-compatible object literal until it, well, parses it.
by baddox 7y ago
The runtime can't know whether it's parsing a plain old JSON-compatible object literal until it, well, parses it.
- pbhjpbhj 7y agoIANAProgrammer but couldn't it do like try..catch and assume it's JSON compatible and fall back to the [much] slower method if the parse fails? Does that cost too much time/resources?
- daleharvey 7y agoThat would make all JavaScript that has non JSON object literals (most JS code) slower
- pbhjpbhj 7y agoHow much slower? We already established it's far slower parsing js; in most cases JSON parsing would fail - IIRC - on the first character ^[^{] ... so would it be worth being slower by the time it takes to check the first character, and then only JavaScript that started with { would be slower. Which I guess is virtually none. I suppose those sorts of questions are part of what makes language design interesting.
- baddox 7y agoIsn’t that effectively what a backtracking parser does? My naive guess is that’s already roughly how the JS parser works, and that process is what makes it slower than the simpler JSON parser.
- epicureanideal 7y agoSounds like some sort of compiler hint like ‘expect json’ or ‘use json’ right above a json literal would be useful. Assuming it matters enough to be worth it.
- vbezhenar 7y agoJSON.parse sounds like a good compiler hint :)