Optimizing Ruby's JSON, Part 5

submited by
Style Pass
2025-01-04 22:30:03

In the previous post, we showed how we eliminated two malloc/free pairs of calls when generating small JSON documents, and how that put us ahead of Oj when reusing the JSON::State object.

But that API isn’t the one people use, so if we wanted to come out ahead in the micro-benchmarks users might perform themselves, we had to find a way to get rid of that JSON::State allocation too, or to somehow make it faster.

Because that JSON::State allocation, isn’t just about any allocations. In Ruby, everything is an object, but not all objects are created equal. In previous parts I touched on how some objects aren’t actually allocated, and called “immediates”, I also touched on how core objects like String and Array has both “embedded” and “heap” representations.

JSON::State is a type defined in C from the extension, using the TypedData API. Peter Zhu has a great blog post that goes in-depth into how these work and how to use them, but I’ll offer a quicker explanation here.

Leave a Comment