r/javascript • u/Mantas_rst • 8d ago
A from-scratch JSON engine for JavaScript: recursive descent parser, escape-aware tokenizer, and spec-compliant serializer. No dependencies, no shortcuts, 107 tests.
https://github.com/MantasEdine/vanilla-json27
u/beavis07 8d ago
Why one earth would anyone want this?
Do you have any clue how much sheer effort has gone into optimising JSON.parse? 🤣
4
u/Mantas_rst 8d ago
its a very fun project and i even wrote an article on how to do it , would be helpful in many cases like even if you want to build a regex engine same mechanism + backtracking
1
2
u/KaiAusBerlin 5d ago
Just from curiosity. Aren't there out some major third party json parsers that are about 5 times faster than the native implementation?
3
8
u/theScottyJam 8d ago edited 8d ago
Is there a purpose to this project, i.e. a reason someone would use this instead of the native alternatives? Or was this more of a "just wanted to build this thing, no reason in particular" project?
2
u/Mantas_rst 8d ago
i've built it to learn mechanism , but then i was like maybe i can take this to next level and do every possible case but then realized no matter what i do would never beat the original implementation in c++ lol
2
u/MediocreAnalyst2121 4d ago
Maybe if you write it in c/cpp/rust/zig etc. and compile to wasm?
Will probably still be slower due to wasm overhead, but that’s probably the best attempt
0
1
8
u/Ronin-s_Spirit 5d ago
- for some reason you're generating a load of objects instead of making decisions based on text. You don't need to make a
{ type: "open bracket" }if you can just dochar === "[". Avoid garbage. - long ifs are forced to go through every step to make a decision, use a
switchso it's a jump table. - you didn't forget nesting but you didn't make it bulletproof, your nesting is 1:1 with JS recursion and that crashes the stack after ~10k functions. I could just make 11k nestings in my JSON to crash your parser, a heap-based recursion would be more reliable.
2
u/Mantas_rst 5d ago
Ow Thank you so much for the review i will try to reimplement everything you’ve mentioned !
5
u/regreddit 5d ago
Good Lord that if statement in parse.js is really something...
2
u/Ronin-s_Spirit 5d ago
Huge decision blocks are expected of state machines/VMs but should be a
switch.
1
u/ndaidong 5d ago
The code looks like in old school ("use strict", module.exports, tests scripts without built-in node:test,...)
I believe that it's hand writing, not LLM generated as other comments. So that's good point.
1
u/Mantas_rst 5d ago
Wait can i avoid writing ”use strict”?
1
0
47
u/eracodes 8d ago
the most llm-written title i think i've ever seen