4 ms·
How the heck is this faster? What's going on underneath? This violates the hell out of Principle of Least Surprise lol
by pmarreck 7y ago
How the heck is this faster? What's going on underneath? This violates the hell out of Principle of Least Surprise lol
- taylorlapeyre 7y agoSince JSON’s syntax is much simpler and smaller, it’s faster to parse a very large object as JSON and return the newly built JavaScript object rather than parse the object tree in JavaScript, which has a much more complex syntax parser. Obviously there’s diminishing returns for smaller and smaller objects.
- gmueckl 7y agoThe Json version only requires the full, complex JS parser to find the end of the string parameter. The string itself is then passed to a specialized Json parser that is faster because the language is a lot simpler and it has to check less possibilities at each point. Apparently this is faster than running the whole string through the full JS parser that has has to deal with all kinds of portential shenanigans in that block like references to variables instead of literals etc.
- vbezhenar 7y agoBut that only applies to the parsing step. With JSON.parse you will parse it every time the code executes, so if that code is in function, JavaScript probably will be better, because compiler can't just optimize out JSON.parse (because someone might redefine window.JSON object or redefine its parse property).
- hedora 7y agoThat’s why you should put all your json literals at the topmost scope in the file. After all, global variables are the best variables. (Per the article’s advice, unless I’m missing something)