| The other day I come up with an idea to serialize JSON in a pretty fast way. I will share it in the hope that someone will find it useful. (From a Node.js perspective)
Traditionally the serialization of objects is made possible by the native JSON.stringify method.
What it does is very simple:
- evaluates every property
- evaluates every value corresponding to that property
- parse strings looking for unwanted characters
- concatenates a long string based on properties/values found This serialization technique performs a lot of subsequent concatenations. So I scratched my head to find a workaround for performing a smaller number of operations yielding the same result. If you know in advance the schema of the JSON that is going to be serialized you can do a little trick. In order:
- You build a schema defining the JSON structure
- Transform the schema into a string
- Transform the string into a template So, when serializing:
- You are basically filling the blanks of your pre-made template
- Done. It turns out that this serialization method is exceptionally fast. In some use cases, you can see a performance improvement of 10000x on native JSON.stringify (benchmarks below). Clearly, this method has limitations. E.g. you can serialize only objects with a fixed structure.
But, if you are dealing with objects that don't change much, it can save you a ton of time. I wrapped it in a github repo (with benchmarks):
https://github.com/lucagez/slow-json-stringify Happy serialization everyone! |