✅ How to deserialize as fast as possible?
I'm trying to get all messages from batch and deserialize it without multiple deserializer calls.
I have following and it's doesn't work:
I know I can do this but it is not optimal:
18 Replies
What makes it not optimal for you?
JsonSerializer.Deserialize in each message from batch
But what's the issue with multiple calls to Deserialize?
why multiple if we can do it only 1 time
like JsonSerializer.Deserialize<List<string>>
Well that's not how Deserialize works, so again, why are you against multiple calls?
so how does it work?
It takes a single string or stream and returns an object, not an array of strings.
this feels very $xy
Using source-generated deserializer is likely to have more impact on performance tbh
Though, ig, you are deserializing into plain strings
I just wanna serialize batch as fast as possible so thats why I'm here with my question
This is my code:
Using source generation to remove the runtime reflection overhead will net you far more perf than removing a handful a calls.
Especially when you thus far have not articulated why having a couple extra calls is a problem.
I mean one call is always better than "couple extra calls"
We're talking micro, maybe even nanoseconds difference here.
The runtime of deserializing the JSON will utterly dwarf the overhead of a few extra method calls.
What should I use to deserialize faster?
There's been two mentions of source generation so far
So, chances are, this
ah, okay, thanks
How to use source generation in System.Text.Json - .NET
Learn how to use source generation in System.Text.Json.
ookay u were right
this is my benchmark:
| Method | Mean | Error | StdDev |
|------------------------ |---------:|---------:|---------:|
| JsonSerializerSelect | 10.12 ns | 0.155 ns | 0.145 ns |
| JsonSerializerSourceGen | 10.35 ns | 0.203 ns | 0.190 ns |
| Utf8JsonReaderGetString | 10.02 ns | 0.051 ns | 0.042 ns |
pity