A New JsonSerializerOptions Every Call Cost Me 120x
A list endpoint on one of my services started showing up heavier in the traces than it had any right to be. It pulled a small object, serialized it, returned it. The payload was tiny — an order with three line items. But under load the thing allocated like it was streaming a video, and the CPU time didn't match the shape of the work. I went looking for the expensive query. There wasn't one. The…
A programmer noticed a significant slowdown in a list endpoint on their service, which they traced back to a new JsonSerializerOptions being created on every call. The JsonSerializerOptions object was thought to be a simple settings bag, but it turns out it builds metadata for serialization when first used and then caches it. Creating a new options object for each serialization call resulted in the serializer rebuilding its entire type model, leading to 120 times slower performance and 42 times more memory allocation compared to reusing a single cached instance.
To optimize the code, the programmer moved the JsonSerializerOptions creation outside the method, building it once and reusing it for all serialization calls.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.