4 ms·
I hate that this micro performance hack actually is better - why don’t they just fix this in the JIT so that the literal is just as fast as the JSON parse? Why
by outside1234 7y ago
I hate that this micro performance hack actually is better - why don’t they just fix this in the JIT so that the literal is just as fast as the JSON parse? Why do we have to think about this?
- badamp 7y agoIt isn’t a jit issue it is a parsing issue. Also micro performance becomes macro at scale. This is not something that you worry or think about with a handful of literals. It would be good for an inner loop or code generator.
- whatshisface 7y agoYou wouldn't write this in an inner loop, you would do it once in the entire program. It's a literal object that doesn't change.
- baddox 7y agoThe 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 :)
- kiliancs 7y agoWhile it's possible that there's room for improvement, it makes sense that parsing a subset of JS (JSON) is faster than parsing JS. JSON is just so much simpler.
- bzbarsky 7y agoThis is happening way before the JIT phase, at the parsing phase. And the reason it can't be as fast as a JSON parse is explained in the article: The grammar of JSON is much simpler. The literal parser in normal JS needs to deal with things like: const data = { foo: /* something*/ 42, [barRef]: 1337 }; so needs to do more branching than a JSON parser. And yes, you can pre-scan the string to make sure it's not doing anything like that... but that probably already costs more than the tokenizer phase of a JSON parse, and it's overhead you still need to do that a JSON parse doesn't have to do.