High Performance JSON Serialization in C# 11 / .NET 7.0
Explore modern C# features for efficient JSON parsing & generation, using code generators and balancing performance with ease of use in .NET apps.
About this talk
JetBrains .NET Day Online 2023
In this talk, you will see how features added to recent versions of C# can dramatically improve parsing and generation of JSON data compared with longer-established .NET JSON handling mechanisms. You will see how to use high-performance memory-efficient techniques, and also how code generators can reduce runtime overheads. This talk will explore the trade-off between maximizing performance and ease of use and will show you how to choose between the various options now available in modern .NET applications.
Read the transcript
Introduction to JSON performance
Thank you everyone for coming and listening. I'm going to be talking, as it says here, about high performance .NET JSON serialization with code generation. So I am going to be talking first of all about the performance issues that exist around what you might call old school JSON serialization, so anything using the Newtonsoft JSON, Json.NET libraries. They're great, but they're not as fast as they could be. So we're then going to look at what has changed since then. How do we do things if we're targeting modern .NET? So what are the options in today's .NET 7, what's it going to be like in .NET 8, and we're going to look at the performance enhancements that are available there, and we're going to see why they're able to go so much faster than the Newtonsoft versions of these libraries.
We're also going to look at how the .NET SDK includes functionality that can take advantage of C# code generators to improve certain aspects of JSON serialization performance, and we're going to look at where that does help and also where it doesn't, because it's quite targeted, the way in which it can improve things. We're also going to look at how you might go beyond what the SDK does and use some open source code generators to provide very high performance JSON deserialization in a way that has a lot of the benefits of regular serialization, but with some of the performance normally associated with much more kind of difficult APIs. So it kind of brings the best of both worlds, and we're going to look at how that's possible and how it works.
Problems with Newtonsoft JSON
So let's start with Newtonsoft JSON. What's up with it? I mean, basically Newtonsoft JSON is great. It's everywhere. It's one of the most popular .NET libraries out there. Like forever, it was at the top of the NuGet package list because everything used it. So Newtonsoft.Json, or Json.NET as it's sometimes also known, hugely popular, does everything you might want of a JSON library. So what's the problem? Why aren't we just still using that? And in fact many projects still are using that. Why might you not, though?
Well, performance wise, it's got three major problems, two of which are kind of fundamental, the third of which could be fixed but probably isn't. The first two are basically inherent to how it works. So the first big problem with Newtonsoft.Json is that it doesn't understand UTF-8. It's been designed to work with .NET strings, and .NET strings do not use UTF-8 encoding. For historical reasons that made perfect sense 25 years ago, .NET uses UTF-16 as its encoding for strings, but that's not how anything out in the wild works.
When you encounter a real JSON document over the network or in a data store or a data lake or whatever it is, it's almost certainly going to be in UTF-8 form. So the first major hurdle that Newtonsoft JSON has to overcome is that the JSON you're going to want to process is going to be in a different encoding than it understands. So you've got to convert it somehow, convert to its format. So that's a problem.
Another problem with Newtonsoft JSON is that it tends to allocate lots of objects and lots of strings. And although the .NET garbage collector is pretty good, it does an amazing job, the fact is that the more work you give the garbage collector to do, the less time your program can spend doing useful work. And so it's fundamental to some aspects of Newtonsoft JSON's design that it can't really avoid quite a lot of the allocations that it does, and these essentially limit the performance it's able to offer. And the third thing is that its serialization engine relies on reflection, and that has some issues. It's not the biggest of the three, but it is an issue. And all three of these things are addressed by the modern .NET JSON APIs.
UTF-8 versus UTF-16
So let's look at a bit more detail about why some of those things are actually a problem. Here is some JSON. So this is a very straightforward JSON object. If you look at it closely you'll see the top level is an object. It's got a property called name whose value is a nested object, and one of that property's nested values is an array. So it's not massively complicated. It's got a little bit of structure, like most real JSON objects will have, and so this is typical of the sort of thing we might want to process. I mean, maybe we're going to process 10 million of these things because they're sat in a data lake, but the basic structure might be just like this.
So here is what it looks like in UTF-8 form. That might be a bit of a blur. The actual numbers aren't hugely relevant, but basically that shows you roughly how many bytes there are going to be for that much JSON. But as I said, Newtonsoft.Json works with .NET strings, and .NET strings don't use UTF-8, they use UTF-16. So one of the things you're going to have to do to work with Newtonsoft JSON is to get your JSON data into .NET string form, and this is how big it looks in UTF-16. It's twice the size, and if you peer closely you'll see half of those are zeros, because that's what you mostly end up with with most JSON.
Now if you've got large volumes of non-English text then maybe it's not so inefficient, because UTF-8 does get bigger as you use non-ASCII characters, but most JSON certainly has a high proportion of ASCII range characters. So in practice your data can easily grow to be twice the size just in the process of converting it. So there's already two costs up front. One, the cost of conversion, and two, the cost of storing, you know, three times as much memory as you really need, if you've got your original data and a copy that's twice the size. So you're already starting on the back foot before you've even begun to look at the first character.
Allocations during deserialization
Now let's look at what happens if you try and deserialize this with our sort of performance goggles on. So let's say we've decided we've got a .NET type that represents the structure of the JSON data that we're looking at, and we just want to convert that JSON data into an instance of that .NET type. Pretty straightforward, right? That's how we tend to do it with JSON. So this is a person object. It's got a name and a birth date, and that name, if you look at the JSON, is actually a sub-object broken down into a given name, family name and so on. And so when we deserialize it we just expect those properties to be populated.
And actually that's quite a lot of objects, right? Because we've got an object to allocate for the person name. That's got three more properties. Two of those are strings, another one's an array with two more strings again, and the birth date's yet another string. So we've got one, two, three, four, five, six, seven, eight .NET objects just for this one bit of JSON. It's not horrible, but it is a fair amount of data to allocate, and if you're dealing with very high volumes of data you can start to give the garbage collector just too much work to do. You can basically end up spending huge amounts of time in the garbage collector as it cleans up after you, and that's not ideal. It's not the best way to be spending our CPU cycles.
Now some of this overhead is inherent to this style of serialization. This really isn't specifically Newtonsoft JSON's fault. You can deserialize in exactly the same way with System.Text.Json and you will have all the same problems for the same reasons. You know, you're going to have to allocate this many objects if that's the structure you're looking for. But there are also some Json.NET specific overheads, largely around the data format that's coming in. So let's take a look at what this means in practice.
Newtonsoft JSON benchmarking
Slight pause there, because we have discovered every time I switch windows we get a slight break in the audio, so I will stop talking every time I switch windows, sorry, but we weren't able to work out how to stop that in the tech check today. Anyway, I have a benchmark. So I'm using BenchmarkDotNet here to measure the performance of various things. I'm going to kick this off running right now so that by the time I finish describing what's going on you will hopefully be able to see the results. So that's going to run in the background.
So what do my benchmarks do? Well, they all basically do the same thing. I've got several benchmarks that are all trying slightly different ways of doing the same thing. They're all essentially looking through an array of objects for a particular value. So let's look at the data that gets set up first. I'm going to go into my base class. So the job of this base class is to set up this array here. So before every single test runs and before the timing starts, this constructor here is going to run and it's going to populate this array with the JSON data that I'm going to parse as part of my test.
So what's going to go in here? Well, basically 10,000 objects. So here's the actual .NET version of the data that we're going to load into the array, this PersonSerializable class. This is basically a .NET representation of the exact same JSON data structure I was just showing you on the slide. So we've got a date of birth property, we've got a nested property representing the name, and inside that we've got given name, family name and an array of other names. So it's basically exactly what you were just seeing on the slide, but in .NET type form.
So this loop down here just creates 10,000 of these things and is going to write all of them into that JSON UTF-8 thing down here, so we end up with a great big JSON array. Now this part's not being timed. This is part of the test setup. This is just giving us some data to look at, and the main thing to know is that every person here has a different name. So we're going to create 10,000 entries. The first one is going to be called Arthur1, because we stick an i on the end, then Arthur2, Arthur3, Arthur4 and so on. So they've all got slightly different names, they've all got slightly different birth dates, and so they're all just slightly different from each other.
And then our tests basically are going to parse that UTF-8 data. They're going to then somehow get that data into a form that we can wrangle, and the different benchmarks do it in different ways, and then we're going to look for a particular piece of data in that array. So we're going to look for the item whose given name is Arthur5000. There are 10,000 entries in my array, so that one's going to be right in the middle, so we only actually need to look through half of the data to find that thing. But this is simple but doing enough work to be representative. We have to be able to parse the JSON, we have to be able to go and look at nested properties of objects in the JSON and work out if they're what we're interested in. So that's not totally unrealistic.
Deserializing everything with JsonConvert
So let's look at what this first one is doing in detail. Takes our UTF-8 data, wraps it in a memory stream, wraps that in a stream reader, because we need to deal with the fact that this is in UTF-8 format and Json.NET doesn't do UTF-8. So the stream reader can be told the encoding and then it can read all the data back out into a string for us. Now some of you might be thinking, hold on, that can't possibly be the most efficient way to pass data into Newtonsoft JSON. I did try a load of different ways and they're all basically indistinguishable in this benchmark. So this was the simplest and was not noticeably slower than any of the others, so that's why I've gone with this. There are some very tiny differences between exactly how you feed data into the deserializer, but they're so small that they make no meaningful difference to this benchmark.
So we get all the JSON data as a .NET string, which remember is going to convert it from UTF-8 to UTF-16, and then we feed that into Newtonsoft's JsonConvert.DeserializeObject method, and we tell it, I would like you to deserialize all of this JSON as one .NET array of PersonSerializable. So my result, I'm expecting that to be an array with 10,000 entries in it, and then I'm just using LINQ to Objects, this data.First. That's the LINQ to Objects implementation of First. It says please find me the first element that matches these criteria, and then we rather arbitrarily return the date of birth.
Why am I doing that? Well, I found that with BenchmarkDotNet, if you don't return something you can occasionally find that the thing you were hoping to time gets optimized out of existence, which rather invalidates your benchmark. So by returning something it makes it harder for the optimizer to get over enthusiastic. So anyway, that's my first benchmark, and let's see how it did.
Benchmark results and garbage collections
My benchmark's finished yet? Let's have a look. And I think I froze again for a second there, but hopefully I'm back. Let's see if we can scroll down to the end of that. Yeah, they're all run. Okay, so wow, that is a lot slower than it normally is, probably because I'm running with the stream stuff simultaneously. However, the basic ratios all look the same, just everything's gone a bit slower than normal. Normally I'd expect this first one to take about 34 milliseconds, and it's done that in every dry run I've done so far today, but now on live it's gone a bit slower. But it doesn't really matter because the ratios between the numbers are all consistent.
So this is our first one. Took 50 milliseconds to process 10,000 entries, so that's about five microseconds per object. And if we look at the memory usage you can see it actually ended up allocating about 22, 22 and a half megabytes of data in order to process those objects, and it's also told us how many garbage collections happened. So these are averages, by the way, which is... you might be wondering what 0.18 of a garbage collection is. That's just the average across the number of times it ran the benchmark.
So this caused an average of about 2,800-ish generation zero garbage collects, 1,272 generation one. These numbers are high. This is a lot of garbage collections for a single iteration of a benchmark that only took 50 milliseconds, so that's not great. On the other hand, you know, five microseconds to parse some JSON's not that horrible. But this next benchmark, 11 milliseconds, is clearly a lot better, so let's go look at that one.
Streaming with JsonTextReader
So this next benchmark, still on Newtonsoft here, starts off similar. We wrap the JSON UTF-8 data in a stream and then wrap that in a stream reader, but now we're going to pass that into this JsonTextReader. This is a streaming API. This doesn't try and decode the entire document in one go. We repeatedly call Read and it passes us the JSON one sort of feature at a time. So we say let's wait for the array to start, and then once we're inside the array keep going until we hit the end, and then individually deserialize each object that we come across, and crucially stop as soon as we find the one we're interested in.
This ought to run a lot faster because this doesn't bother to look at the second half of the objects. So Arthur5000, that's halfway through. It's never even going to try looking at the second 5,000 objects, because as soon as it finds that one it's going to stop. So this should be a lot faster. It should be twice as fast, right, because we're doing half as much work. But actually it's a lot better than twice as fast. 50 milliseconds versus 11 and a half milliseconds. Okay, normally when I run this that's 34-ish and that's nine-ish, so it's a bigger ratio than normal. I think this test runs slightly... normally, though, this is about three and a half times slower than the second benchmark.
Why is it three and a half times slower when it's only doing twice as much work? That's peculiar. Well, let's look at the memory characteristics. So in terms of allocated memory it managed to allocate a little bit under half. The main reason for that is that with this first one it's trying to return me the entire array in one go, and to do that it's actually building up a list object, and it doesn't know how many elements it needs to start with. So it just guesses how many elements might fit, and every time we run out of space in a List<T> it just allocates a new buffer that's twice the size. So it ends up sort of throwing away all the too small buffers it created on the way, so actually it's a bit wasteful. So it's going to allocate more than twice as much memory as the more efficient version, so that's why that's a higher number.
But look at the garbage collect generations. So we've got well under half the number of gen... sorry, gen zero, but the gen 1 and gen 2 are way lower. There's only 15 as opposed to, you know, 1,200 gen ones, and there are no gen 2s here. Now that's really significant. That's the main reason that this second benchmark actually runs so much faster. I mean, yes, it's doing half as much work, but it's going in this case almost five times faster, but usually over three times faster, despite only doing half the work. And it's because it's not clobbering the garbage collector. This first one is way slower than it ought to be because it's spending so much time in the GC.
Why long-lived objects hurt the GC
So let's look at why that is. So going back to the first benchmark, and this will all be relevant when we get to the System.Text.Json stuff, going back to the first benchmark, we're saying I want you to return me the entire array in one go. So what's going to happen as this starts to do its work? This DeserializeObject is going to start churning through the string we've given it, gradually creating objects. Eventually it's going to create 10,000 of these things, and actually we worked out there's about eight sub-objects per thing, so it's gonna create about 80,000 objects. And the garbage collector is going to go, you seem to be creating lots and lots and lots and lots of objects, maybe it's time for a garbage collect, maybe we can get some of that back.
And so it halts the thread, looks at what you're doing and discovers that it can't really free anything much, because this DeserializeObject is gonna have to hold on to everything until it's ready to return it to you, because we've said I want all the data in one great big lump. And so the garbage collector goes, oh, well, you've created thousands of these objects but they're all reachable because you're not done with them yet. It's not going to be able to garbage collect anything until we get to about here. That's the first point where we're not holding on to all the objects anymore.
So this inherently can't free up memory, but the garbage collector doesn't know that until it tries. So it's desperately going, oh, you've allocated so much, I'm going to try again. Oh, that didn't work. Maybe a gen 1 will help. And it hasn't helped either. Maybe a gen 2 will help. Oh, that hasn't helped either. And it just doesn't realize that we're just building objects that are going to live for a relatively long time. So that's not good, and that's causing the GC to behave inefficiently.
Whereas this second one, which deserializes the objects one at a time, so there's no array brackets on this one, we're saying just the current object please, just that, deserialize that, and then we take a look at it and go, was that the one? If it was, we're done. If it wasn't, well, we should move on, and this object here being returned here is no longer reachable. So if the garbage collector does run, it will be able to recover that memory. So this usage pattern is much better suited to the way the garbage collector expects things to run. You will allocate objects and then almost immediately cause them to be unreachable, and the GC is really good at that. It copes very well with very short-lived objects, which is why this thing goes over three times faster even though it's only doing half the work. We get a bigger boost from the GC efficiencies than we got from simply doing less work.
System.Text.Json overview
Okay, so that's some analysis of Newtonsoft JSON. So now let's take a look at how things look in .NET today. What would you use for JSON deserialization in a modern .NET app that's targeting .NET 7 or .NET whatever? You would almost certainly use System.Text.Json. So this is built into the .NET runtime library, so it's right there. You don't need to add any extra dependencies to get hold of it. You don't need to worry about whether you're depending on a different version from someone else. It's going to be serviced as part of the runtime, so you don't need to worry about security issues being discovered with NuGet packages and all that kind of stuff. Simplifies your deployments.
But it has some advantages in its design, biggest one being that it works directly, natively with UTF-8. So this does not need data to be converted from UTF-8 format into UTF-16 before it can start to work with it, so it doesn't use the .NET native string type internally as it works. But that's not the only thing. It offers a wider range of trade-offs between performance and convenience. So we saw with Newtonsoft that we could either just deserialize everything in one go, or we could use the streaming API to process things one item at a time, and then we could fall back to serialization for each individual thing. Or if you want to, in Newtonsoft you can go streaming all the way, but that actually makes code a lot more complicated. Now those are both options with System.Text.Json as well.
But it also offers a couple of other flavors of using JSON that offer different trade-offs, different places on that trade-off between complexity and performance. So for example there's an API known as JsonElement. It's a pair of APIs really, JsonDocument and JsonElement, and this offers a read-only view over some JSON data. It's basically an object model, except technically they're structs, but it's like an object model. You can't modify JSON with it. You can only look at an existing JSON document with it, but its superpower is that it's very low allocation. It does not allocate very much memory at all when it's working with JSON data.
There is also another object model which is modifiable. So the downside of the ultra high performance read only one is you can't actually generate a new document with it. You can't build up a description of a new document. You can't load a document into memory and then edit it and then write out the edited version. That's not available with JsonElement, but it is available with this other modifiable model, which is not as efficient. It can't be as efficient as the read-only one, because being able to support modification comes at a cost, so it's not free, but it's still pretty efficient.
And it also, as I say, supports serialization and streaming, just like Newtonsoft does as well. So you've got those benefits. And also it's possible to get System.Text.Json to do compile time code generation to drive its serialization engine instead of using reflection. It will use reflection by default, but you can make it not use reflection, and that improves performance in certain ways that I'll discuss when we get to that. So these are the differences. Now let's start to look into that.
System.Text.Json benchmarks
So let's take a look at our benchmark. So this is the Newtonsoft one. If we scroll down a bit, the next one here, find whole array System.Text.Json deserialize. This is basically exactly the same idea as our first benchmark. If I quickly scroll back up to the first Newtonsoft one, what did we do? Well, we loaded in the entire UTF-8 data, passed the whole thing, deserialized it as a PersonSerializable array and then used LINQ to Objects to find the object of interest. And this third benchmark here does precisely the same thing. We are deserializing all of the JSON into a PersonSerializable array and then we're using LINQ to Objects to find the item we wanted.
The only difference is we're now using System.Text.Json's JsonSerializer to do our deserialization. Notice we can pass the UTF-8 data in directly. There is no need to do any sort of conversion before we do this. Otherwise literally the same code, so the actual thing that processes the results is identical to the previous version. So let's see how that compares for performance purposes.
So we're now looking at this third benchmark. Again, usually that's a lower number when I run this, but it's in the same ballpark. So the main thing is it's a fair bit faster than this. Normally I'd expect this to be about 23, whereas this is normally about 34 every other time I've run it today. So for some reason these two have gone a bit slower today. Don't know why, they just have, probably because I'm sharing my screen. But look at the memory usage. The Newtonsoft JSON one took over 22 and a half megabytes, whereas the System.Text.Json one 4.86 megabytes, a lot less.
And a big chunk of that is down to the fact that it hasn't had to convert it into a UTF-16 representation. It's been able to just use the UTF-8 data exactly as it is and hasn't had to kind of convert to .NET strings before it even begins to parse the JSON. Now it is still having to do some of that conversion, because we've asked it to deserialize this into objects. Some of those objects have string properties, and so the values of all of those properties are going to have to be UTF-16 strings, because they're .NET strings. However, most of the JSON data isn't actually string values. Most of it's like structural, or it's property names or stuff like that, so the amount of data that it's had to do that for is much smaller and the memory footprint is correspondingly a lot lower.
And this is reflected in the garbage collection cost. So whereas the Newtonsoft one caused over 2,800 garbage collects in gen zero alone, our System.Text.Json version of the same thing was just 687 and a half on average. The gen one is similarly lower, so 1,272 versus 625, so that's about half, and the gen twos are also lower. Now it's not ideal. You don't really want any gen twos if you can help it. You don't want that many gen ones. But it's certainly better than this, and that accounts for a significant chunk of the performance improvement.
A faster library won't fix bad decisions
Now what you would have noticed is that this first attempt at System.Text.Json is actually quite a lot slower than our second attempt in Newtonsoft JSON. So what this illustrates is that upgrading to a faster library probably isn't going to save you from bad performance decisions, because the fundamental problem with this first one also exists in this second one, which is we're asking to deserialize all 10,000 objects before we even look at them. And that causes two problems. It means first of all these end up deserializing 5,000 objects they never even look at, because the object we're looking for turns up about halfway through the data, so that's a waste of effort. But also the fact that we're asking these two things to both return us one massive array with everything in it all at once is responsible for this garbage collection pattern, the fact we're seeing lots of gen 2 collects.
So simply upgrading to System.Text.Json isn't going to save you from yourself. If you are making certain kinds of mistakes before and you carry on making those same kind of mistakes today, you'll have the same kind of problems. I mean, I'm calling it a mistake, but maybe it doesn't matter. If you are not in performance critical code then, you know, who cares, it's fine. But this is a talk about high performance JSON processing, so presumably you do care about the perf, and this is not a good look.
So it's definitely significantly faster than the direct equivalent in Newtonsoft. It's definitely a lot lower memory consumption than either of the Json.NET ones. Even the efficient Json.NET one still took nearly twice as much memory as our inefficient System.Text.Json one. And that's interesting actually. The fact that we're allocating less memory could mean that the difference between these two in this simple test would actually look a lot closer in the context of a real application, just because the amount of allocation you do has a system-wide impact.
Per element deserialization with JsonDocument
But let's look at this other one, per element System.Text.Json deserialize. So that's obviously better, although you'll notice it's still worse than the Newtonsoft one. I'll explain why. Let's look at the code. So this is the second of the System.Text.Json ones, and this one, it's kind of similar to the second Newtonsoft one. So the Newtonsoft one, we basically blast through the array one object at a time and deserialize them, and then we stop as soon as we find the one we're interested in. That is kind of what's happening in this new one. So we're sort of looping through all the elements in the document, deserializing them one at a time and stopping when we find the one we're interested in.
So it's pretty similar. It's not quite the same though. We're not using the streaming API here. We are going one element at a time through this JsonElement API, and this comes from JsonDocument. And you'll notice we begin by saying JsonDocument.Parse all of the UTF-8. So we are actually, logically speaking, saying please read the whole document in. Now it doesn't deserialize the whole thing, but when you load data into one of these things it does actually do a certain amount of processing. It essentially builds up a little kind of index in memory to keep track of where everything is in the document, so that all subsequent operations, everything you do with the JSON in that document, will then go faster as a result.
But it does mean in situations like this, where we don't even look at half the JSON, this is actually doing a bit more work than it really needs to. That's part of the reason why this one is not as fast as our best Newtonsoft JSON effort. But don't worry, we will get much faster than that. So what is this doing? We're saying I'd like to read the whole thing in as a JSON document. I then like to retrieve the root element, and I believe that's an array, so I'd like to iterate over all the elements in that JSON array.
This will throw an exception if I turn out to be wrong about that, by the way. If I'm mistaken and it's actually just a string or an object at the root, that just won't work. But it is in this case, so that's fine. And then for each element in the array, then we're going back to deserializing. So we're deserializing one at a time and bailing as before. So that's the code.
Now let's go back and look at the benchmark results again. So I believe the reason it's actually a teeny bit slower than the Newtonsoft version is because of that initial document parse, where it does look at the whole document. So this is at a slight disadvantage. However, it's using a lot less memory, only using 4.6 megabytes as opposed to the 9.3 that is being used by our best Newtonsoft effort. And the garbage collection counts are much better. Not only is it the lowest gen zero count we've seen so far, only 546 and a bit per test iteration, so about half what the best Newtonsoft effort was able to achieve, but also no gen 1 or gen 2 collections, and that matters more.
So you might find that even though these two benchmarks look fairly closely matched, the fact that this one is making the garbage collector work much less hard might mean that on average your application performance goes better, because the garbage collector is not having to step in and sort of freeze threads as often as it has to. It's not having to move data around as often as it otherwise would do. So the collateral damage that this one does by allocating twice as much memory might actually have a larger impact on your overall app performance than is visible through these kind of micro benchmark measurements.
JsonElement API performance
You're obviously looking at these two down here. Why am I talking about these slow ones up here when there are clearly some better ones available down here? Okay, let's talk about this next one, and I'll get to that in a second because that's not as simple as it looks. So this next one, that's a clear winner, you know. So that's saying four. Again, these numbers are different from what I've seen every time from this test recently. Normally I've seen that come out as about three and a half, so it's about 10 times faster normally than this one here. Yeah, not far off four milliseconds and fifty, so an order of magnitude faster, even with these slightly wonky test results I'm getting today, and, you know, three-ish times faster than this version.
But wow, look at the memory. 222 bytes. Just to remind you what this test is doing, this test is looking through ten thousand JSON objects in an array, and it's allocated 222 bytes of memory to do that. That's not per object. That's 222 bytes to process the entire JSON document, so less than one byte per object on average. That's clever. We'll talk about how it does that in a moment, but let's look at the code first.
So it's this next one, find System.Text.Json JsonElement. That's not a typo. So this benchmark is System.Text.Json and we're looking at direct use of JsonElement. Now it starts off the same way as the preceding test, so we basically load the whole thing into a JsonDocument and we go looking at the root element like we did last time, and we're still using the EnumerateArray as before. But now I'm actually using LINQ to Objects again. I'm just using the First operator to find the first thing that matches my criteria. But the big difference here is I'm not deserializing individual objects.
I still want to do the same thing. I want to look at the name.givenName property and see if it's equal to that, but I'm not going to do that through deserialization this time. I am going to use the JsonElement type's methods. It offers a TryGetProperty method, which says, is this an object and does it have a property of that name? If it does, please return true and put that property, the name value pair, the whole property name value pair, in a new JsonElement here. And then if that worked we're going to look at that new JsonElement that holds that name property value pair and say, well, is your value an object and does it have a given name?
And if so, well, we'll... sorry, I misspoke. These are not pulling out the key value pairs, these are pulling out the values, sorry. There's a separate way to get the property without the value. So yes, sorry, this first one gets the value of the name property if it's there. The second one then drills into that to get the nested given name. So we're doing name.givenName, but we're just doing it without using serialization. We're just saying, well, I just want to go looking for these properties by name, and if that succeeds then we say, well, okay, I'm expecting this to be a string. Is it equal to this value here?
Why ValueEquals avoids allocation
Now this one's a little more subtle. Up here I'm using serialization, so I'm saying please just take the JSON and turn it into a .NET object, and then I'm just retrieving the given name property and using ordinary string comparison to say, is this the one that I'm looking for? For this to work, that given name property has to contain a string. It has to have a string in it. So I'm forcing this deserialize method to create a .NET string object for every single given name property of every JSON object that's in that thing there. So it's going to have to allocate 10,000 strings for this code to work.
But here I never actually asked for the property value as a string. I'm saying give me the JsonElement that represents that property value, but I'm not going to ask you to turn that into a string. I'm saying, can you just tell me whether it is equal to this other string over here? Why does that matter? It matters because this does not need to allocate anything on the .NET garbage collected heap. That's a string constant. It's going to be interned. There's going to be exactly one allocation of that string across the entire lifetime of the process, so, you know, that's essentially free once you're up and running.
And this thing doesn't convert the underlying JSON data to a string. Instead, character by character, it looks at the JSON data. It just says, is the stuff in the JSON the same characters as this string I've got here? Never allocates a .NET string. It just compares an existing string I passed in with the raw UTF-8 data. Now it is having to do some conversion there. It is actually having to convert from this .NET string format into UTF-8. We could actually avoid that, by the way. You can stick this on the end of a string in recent versions of C#, and that will then actually end up passing this as a byte array of UTF-8 data, which will go a little bit faster. But actually for the purposes of this discussion that's not the most important thing.
The most important thing is that this code doesn't allocate anything except for the iterator that is required by LINQ to Objects to do this First thing. Each of these JsonElements is a struct, so they don't need to live on the heap, and the way I've called it here they're all going to end up being hidden local variables. They're all essentially going to live on the stack frame. So there's no heap allocations done in this code other than the one for LINQ to Objects, which is why our allocation is just a couple hundred bytes for the whole thing. That's basically LINQ consuming that, and it's not nothing, but it's very little compared to the others. 220 bytes as opposed to several megabytes, it's a big step forward. That's a large part of why this goes so fast.
So you can see it allocated so little that the garbage collector never felt the need to step in and do anything. Phenomenally efficient. And we were parsing ten thousand, well, five thousand records really, because we skipped the second half really, we're not fully parsing all of them. So we're looking at 5,000 records in a millisecond, so that's less than one microsecond per JSON object. Now I find that phenomenal. I find it mind-boggling that it's possible to do meaningful processing of a JSON object in under a microsecond.
When I first started using computers in the 1980s you couldn't execute a single machine language instruction in a microsecond. Yeah, it took several clock cycles on CPUs that had clock speeds measured in megahertz to do anything at all. And so the idea that you can interrogate the structure of a JSON object and compare one of its values with something in less time than it takes to execute one instruction on a computer in the 1980s blows my mind. I mean, that's Moore's law for you, admittedly. Well, actually, technically not Moore's law, it's the other law of computers getting faster and faster, which is not the same thing, but I digress.
Deep dive into JsonElement and Utf8JsonReader
Anyway, it's very, very fast. It's certainly a lot faster than our first attempt. It's an order of magnitude faster, and the memory efficiency is pretty good. However, obviously all of you are going, why isn't he talking about this one? This one's obviously even better, so maybe this is the one you want, because that is way faster. 50 bytes, look at that, and that's almost nothing at all. 50 bytes to process 10,000 rows of JSON. This has got to be the one, right?
Let's take a look at this. How much do you want this method? Here it is. A bit more of it. Still want it? How about now? Still a fan? Nearly there. And rest. Okay, that was kind of complicated. This is using the streaming API in System.Text.Json. So we are using a Utf8JsonReader, which is this thing here. It's really, really fast, and this is what underpins everything else, by the way. Anything you do with System.Text.Json to read JSON ultimately relies on this thing at some level. They're all just wrapping it to various extents. So this is the basis of everything.
And a bit like the earlier example, we just repeatedly call Read, saying please move to the next item, and we check that it starts with an array. But this has got a lot more complicated, because we're not then falling back to serialization once we get to the individual objects. We're doing the whole thing streaming wise, and the big problem with that is you have no idea what order the data will show up in. It's going to be valid JSON, but the properties won't necessarily be in any particular order, because JSON doesn't require ordering. Basically you're not allowed to say, oh, you've got to put your properties in a certain order otherwise I won't talk to you. That's not really permissible in the JSON world.
So we have to be ready for things to happen in any order, and it gets a bit weird and complicated because we've got nested objects. We have to remember, were we in the middle of the nested name type, or are we still in the outer object, or are we actually up in the array waiting for the first object to appear? So we have to keep track of how deep we are in the JSON right now. What have we already seen so far for this iteration? Did we already work out that this is not the one we're looking for, but we haven't got far enough through the JSON to be able to skip to the next object yet, because we're still embedded several layers deep? It all gets really complicated. You basically end up having to build a little miniature state machine just to keep track of everything that's going on.
And the huge problem with this is it's not at all obvious what the code is doing. Yeah, there's no obvious relationship between the structure of this code and the actual goal. Yeah, so somewhere buried in here... is it here? No, it's not here. Somewhere, I can't even find it now. There it is. But that's the actual line that matters, that's happening there, but to get to that line was... sorry, no, it's not even that. I've got it wrong twice now. There it is, sorry. Arthur5000, that's what we're looking for. So this is the actual logic, and everything else is just complexity mandated by the fact that this is a streaming API and we're in no control over the order in which we see things. So for this reason people often decide that actually the performance boost you get from this thing just isn't worth it.
It might be... that's a business decision, you know. It depends on how much your performance is worth to you. Is it worth the extra development overhead it takes to create that in the first place, and the extra maintenance overhead involved in having an almost completely unreadable bit of code that's going to be a nightmare to maintain? Are those costs justified by the performance improvements? Now if you are processing trillions of records of JSON, those performance improvements could well translate directly into lower cloud computing costs, at which point the answer may be yes, this pays for itself 100 times over, of course we're going to do it this way.
If that's not what you're doing, it might be that the much easier development path of doing it this way means that this is the preferred one, because this JsonElement thing gets you most of the way there. That's more complicated than the serialization approach up here, but it's not much more complicated. So maybe this is the way. Maybe... oh, foreshadowing of what's coming later in the talk, maybe there's a better alternative. However, for the time being that's enough of this demo. I'm going to go back to my slides and talk in a bit more detail about how it is that the JsonElement is able to achieve this remarkable performance.
How JsonElement avoids copying data
So just remember what we've seen. It was able to process 10,000 rows of JSON, apparently not having to allocate any data on a per object basis. It was like 222 bytes up front and that was it, no more allocations. How can that work? Well, there is a basic principle in operation here, which is that JsonElement never makes copies of data. We don't copy data, we just point to some data that was already there. So the basic observation that JsonElement is making is this. You've already got all the data that constitutes your JSON document right there. It's that big blob of UTF-8 data. It's all there. We don't need to store it somewhere else because it's all there in the source document.
So we don't need to copy the property names out into .NET strings. We don't need to copy the property values out into other objects. They're all right there. So when you ask the JsonDocument for the root element, what does it give you? It gives you a JsonElement that says, I represent this range of text in the JSON, all of it in this case because it's the root element. I represent everything from that opening brace to the closing brace, or in the example of my benchmarks, everything from the opening square bracket to the closing square bracket. So I'm all this data here, and it knows that it's a JSON object.
If you ask this to give you the name property, it will return you another JsonElement that represents just that section of the JSON that is the property. So in this case I've called get property. This does return the name value pair, so this gives me both pieces, quote name quote, that's the property name, and everything after the colon, that's the property value. And then if we ask this thing for its value, we get another JsonElement, which is just the bit after the colon. This is an object. If we ask this for the given name property, it's going to give us just that slice, and if we ask that for just its property it's going to give us just that piece there.
Every single one of these things is pointing to the same lump of data. It's all pointing to the same UTF-8 array. It just points to different subsets of it. It's just saying, I'm just this piece, I'm character, you know, 47 to 95 or whatever it might be. They're all just referring to the one and only copy of the underlying data, and they're all struct types. They're all value types, which means it is possible to use them in a way that they never have to live on the heap. It's not true that structs always live on the stack. That's a popular misconception, but it's possible to use them in a way that doesn't cause any heap allocations. So that is what enables these to go so fast. They don't ever make copies of the data.
Reflection vs code generation
Now let's talk about the other performance oriented feature that System.Text.Json offers that you don't get in Newtonsoft JSON. This is to do with reflection. So by default the reflection mechanisms in both Newtonsoft JSON and System.Text.Json, they both do the same thing. They both use reflection to discover what properties your .NET types have. So when I said please deserialize this JSON array into an array of PersonSerializable objects, it would have gone, okay, what does the PersonSerializable look like? Oh, it's an object with two properties, name and date of birth. What does name look like? Oh, that's another .NET type. That's an object called a PersonNameSerializable. It's got three more properties, and so on.
It uses reflection to discover the structure of my .NET object, and that's what drives the behavior of the serialization engine. It's very convenient. We can just write a .NET type whose structure reflects the structure we expect in our JSON and it just works. That's great. However, there are some problems with this. Reflection has a bad reputation for speed, which is partially deserved. It's actually not as slow as a lot of people think.
I mean, it's definitely slow. It's definitely a lot slower to read and write through reflection than it is to just use normal property access, because normal property accesses can, you know, run in nanoseconds, whereas reflection probably tens, maybe hundreds of nanoseconds, maybe even as much as a microsecond. They're not that slow. Yeah, it's not like it's going to take, you know, the blink of an eye to do it. Nothing as slow as that. But it's definitely slower. But actually that's not the real problem with reflection. It can be, but often it's not.
Cold start costs
Often the real killer with reflection is how much it costs the first time you use it. Doesn't always matter, because clever reflection-based things can use reflection to work out what's going on and may actually do compile time, sorry, runtime code generation to avoid the recurring overheads. They're just using reflection to work out what to do and then use code gen to actually do it. That can amortize the costs, but the startup costs for that can be horrible, because it's having to discover everything about the structure of your data types at runtime and then generate code and then get that compiled, and this will take quite a long time.
If you're processing a trillion records you probably don't care about that, because the first time cost is sort of dwarfed by the overall cost of the total job. If however you're writing a desktop application or a phone application, the first time costs really matter, because that's when you make your first impression with users. If the first time the user clicks on a button it takes two seconds before it responds, that's the thing they're going to remember. They're not going to remember the next 10 times on that button that it was nice and fast. They're going to remember that the first time it was horribly slow, particularly if that's true every single morning that they launch the application.
And it's not just desktop applications or phone applications. This can also be a problem in the cloud, because a lot of people run stuff up in cloud platforms in a way where you don't pay when you're not using things. So things like AWS Lambda or Azure Functions, there are billing models where they say if you're not handling requests we're not going to charge you any money, which is great, but obviously they're not going to have hardware on standby for your benefit if you're not paying. So the downside of this is if you have one of these models and your app is idle for four hours, it's not going to be running.
And so when the next request comes in, they're going to have to quickly find a VM to host you on, or a container or whatever, fire it up, start the .NET runtime, load your application, hit your application's entry point and get your app to the point where it's able to respond to a request, invoke the request handler and get a response. All that has to happen, and that can be quite slow, because the first time things happen are often much, much slower than everything else, and reflection is particularly bad for that. Reflection is horrible on first use characteristics. So if that's the kind of deployment model you've got, then not using reflection has its benefits.
So first use performance, cold start performance, it's a big deal. There's also a memory overhead, typically a few megabytes, not huge but not nothing. Also if you're using ahead of time compilation, if you're doing like native AOT compilation, you're likely going to be trimming your binaries to only include the code that you're actually using, and anything that uses reflection makes that a lot harder to get right. So avoiding reflection entirely has some benefits for those deployment models as well. And also there's a separate related feature which can generate high performance output serialization, which is sort of orthogonal to all of this. But anyway, let's take a look at how this works.
Source generators in .NET
So the way they're able to avoid using reflection is through the use of C# source generators. Now this is a feature of the .NET build chain that enables libraries to kind of inject code at compile time. So libraries, they could be NuGet packages or they might be libraries built into the .NET SDK, or maybe both. They're things that get involved in the build process, and they're able to generate code at build time that gets compiled into your application and can then execute at runtime.
So if you're using source generators the build process looks like this. The C# compiler is started. It loads all the files it's been given, all the files your project says to load, and it tries to process them all, looks for syntax errors, then starts to do semantic analysis to work out what it is you mean by string. Oh, it's System.String. And basically resolving all the symbols. But once it's looked at everything, it doesn't necessarily worry if it doesn't have a complete picture, because it says, okay, I've done as much as I can, but are there any generators registered in the build? Are there any source generators that would like to have a go? And there's actually a couple built in to the .NET SDK, one of which is for JSON serialization purposes.
And what these things do is they get access to all of the analysis the C# compiler has done so far. So everything the compiler has done to try and understand the source code is available to these things. They can look at the code and go, I might add some more. I might add some extra source files into the mix. And whatever comes out of your source generator, the compiler will then incorporate those into the build process. Oh, there's some more files, great, let's keep going. And only once it's looked at all of these does it consider compilation to be complete. So this gives source generators the ability to fill in gaps that were there after stage one.
JsonSerializerContext and JsonSerializable
So let's look at how this works with JSON. If you want to use the System.Text.Json features for avoiding reflection, but you still want to use serialization, here's what you do. You write a type that derives from JsonSerializerContext, and then for each type that you wish to serialize or deserialize, you apply an attribute to that class of type JsonSerializable. And this can generate two kinds of code. It can generate property descriptors, which basically contain all of the information that it would otherwise have got from reflection, and it can also optionally generate a high performance serializer. So let's take a look at this. Rather than describing it, it's easier, let's see in practice.
So I have up here a class called TestSerializationContext. I'm just going to quickly uncomment something in the code here, because I have that compiled out by default. Let me go back here now. So as I just said, you need to derive from JsonSerializerContext. That's defined by the System.Text.Json libraries. And then for each type that you want to use in serialization and you don't want the reflection overheads, you add one of these attributes. So I've said I need to be able to deserialize and or serialize PersonSerializable. I also want that to work for arrays of PersonSerializable, and I've also had to include this PersonNameSerializable, which remember is my nested object. So my name property is actually one of these PersonNameSerializable, so I've had to include that in the list as well.
Demo: the generated serialization code
So what has this done? If I come over to my benchmark and look for a particular piece of code. Right, here we are. So here's a benchmark. Wasn't running earlier because it was #if'd out, and it is using JsonSerializer. This one's actually serializing things. It's writing stuff out rather than reading them in, so this isn't directly comparable with the earlier benchmarks, which is one reason I wasn't showing them earlier. And it's saying I would like to write data into this memory stream, and the data I'd like to serialize is this people. This is the same 10,000 elements that we were also reading in earlier. So my benchmark base class just sets up both the UTF-8 data and also the equivalent .NET representation. So this is going to go from the .NET representation out to UTF-8 data.
But notice the context.PersonSerializableArray. So what's that? Well, context is my TestSerializationContext class, and we're using the PersonSerializableArray property. Well, I don't see a PersonSerializableArray property in there. It looks pretty empty to me. However, I've annotated it with partial. That tells the compiler this might not be everything. It says there might be other source files around that are going to contribute more stuff to this class, and that is what enables the source generator to add members to this class. So for every JsonSerializable attribute I apply, it's going to, in a different source file, add members to this.
So if I go back to the benchmark that uses this and say, well, show me this PersonSerializableArray property, I'm going to F12 to go to the definition. This thing here opens. So this tab, you may or may not be able to read that, it says this file is auto-generated by the generator System.Text.Json.SourceGeneration.JsonSourceGenerator and cannot be edited. So it's telling me this is generated code, actually being generated as part of the build process, and so this is extending my TestSerializationContext class. It's adding in extra members, including this PersonSerializableArray thing that my benchmark was using.
So I'm not going to go into huge amounts of detail on this, but if we dig into this a little bit we will find... where is it? Oh, I'm probably in the wrong file here. Yeah, hold on a second, there's more than one generated file. I don't want PersonSerializable, I actually want... sorry, I want PersonSerializable, not PersonSerializableArray, because PersonSerializable was going to be more interesting. Let's go and look at that one. Right, so this one is for not the array type but the actual type itself, and this here is what I was interested in.
So this is basically everything you could have discovered from reflection, saying this is a property, it's public, it's not virtual, it's declared by this type here, it doesn't have a type converter, here are its getter and setter, and so on. This is all the stuff that the PropertyInfo type in reflection would have told you. But this is a dead simple object. This has got very little in it. It's going to take almost no time at all for this thing to be constructed, compared to the milliseconds it will take for the reflection engine to get itself up and running after you start the process. So this gives all the information that it would otherwise have got from reflection in a tiny fraction of the time, and that is the key benefit that this offers. It enables us to get all the information really, really quickly.
Now it's actually quite hard to benchmark this, because it mainly affects first time usage, because once reflection is up and running it's actually relatively fast. So I'm not actually going to show you a benchmark for this. It's kind of better to demonstrate it by deploying stuff up into the cloud and timing your cold start request times, but that takes about four hours to measure properly, so I can't redo that right now. But it does make a difference. It does tend to make multiple milliseconds of difference. Exactly how much depends on how complicated your object models are, but it's definitely a significant improvement for cold start time.
Generated fast serializers with Utf8JsonWriter
Okay, so the other thing, can I find it in here? Oh yes, the other, this one here. The other feature I mentioned is the ability to write data out with a very fast generated serializer. So the other thing you get with this code generator is a method for each serializable type that uses Utf8JsonWriter, which is the write mode streaming API, to enable you to write the data out. And this just basically generates the simplest, fastest possible code that writes data out. So this is also going to be way, way, way faster than trying to use reflection. Streaming is much easier when you're writing than when you're reading, because you get to control the order here. So that's the other thing this will do.
Okay, so I'm going to quickly undo the change I just made there, because I don't want to break this from compiling, and then I'm going to go back to the slides. Okay, so the basic heart of this is that all that code gen creates, or makes available, instances of a thing called JsonTypeInfo<T>, where T is your chosen serializable type, PersonNameSerializable, PersonSerializable, whatever it might be. And this basically only has one public member. It's almost empty from an API perspective. The one public member points to that high speed serializer. It's a delegate that points to the serializer. Everything else is internal, but it gives the System.Text.Json serializer all of the information it needs so that it doesn't have to go talk to reflection at runtime.
Advanced generation techniques
Okay, so that's pretty much it for what's built in to System.Text.Json, but I want to show you another step we can take. We can do better, because what I've shown you so far is either you deserialize things in the most straightforward way possible, but you often end up with a lot of overheads because you end up creating more objects than you might actually need, and you might operate in a way that's quite inefficient for the garbage collector. Or you can start to go a little bit out of your way to get slightly improved performance, or a long way out of your way to get very fast performance. But what if there was a way that we could give a programming model that looked very similar to serialization, but without the problems?
Just to remind you what the problems are. No matter which library you're using, there's a fundamental issue with trying to represent JSON data as .NET objects. In fact there's two fundamental problems, one of which is the .NET type system isn't really a very good match for JSON the way people actually do it with JSON, particularly if they're TypeScript programmers. They'll often say, okay, this thing might be one of these or it might be one of those. It can be two different things and we'll decide at runtime which it is. That's not really a thing the .NET type system is particularly good at dealing with. It doesn't do sum types yet, so that can be an issue.
But even if you constrain yourself to JSON that's easy to represent in .NET, we've still got this big problem of allocations. If you've got, you know, a hierarchy of data like this example I've been using throughout, you've got a bunch of objects to allocate just to represent one record. And strings are a problem in particular, because the moment you force System.Text.Json to give you a .NET string, you're throwing away the advantage that you would have got from its ability to work with UTF-8 data naturally, because you say I want this as a .NET string, so it's going to have to turn it into... it's going to have to turn it into UTF-16, it's going to have to make a copy. So this is fundamentally unavoidable with this model of serialization.
Maybe we're thinking about serialization all wrong though. Could we do something else? Do we have to make our JSON data into ordinary looking .NET types? Could we do something else? Could we maybe generate .NET types that are harder to write, but it doesn't matter because a code generator is going to write them for us, which do a bit more work and work a bit more like the JsonElement API? Maybe rather than making copies of data and turning it into .NET stuff, what if they were just a facade around the underlying UTF-8 data? So what we could do is basically have a thing that looks like JsonElement, only it's sort of strongly typed. It knows about the structure of the data that we actually expect.
Generated wrapper types: benchmark results
What would that look like? Well, to whet your appetite, here's an idea of how that might perform. So these are the same benchmarks I've been running throughout. The benchmarks get slower and slower as I run more of them, which is why I'm not running this one live. You'll notice the numbers are now more like I expect, 35 milliseconds for the just first JSON one. But look down the bottom. The last three are benchmarks that are going to use the new technique I'm talking about, and notice these are all around the sort of three, four, about four milliseconds to process the records. And if you look in the memory allocation side, they all have this ultra low allocation characteristic, and yet they have a programming model that's very similar to serialization. That sounds intriguing. Let's actually see what that would look like.
Demo: strongly typed wrappers generated from JSON Schema
So I'm going to go into my code. I'm going to comment out that thing and take a look. So here is how it could look. So we start off with JsonDocument, as we did with all the other JsonElement-based examples. So you've got to first of all load stuff into a JsonDocument, and that then lets you do this very hyper efficient read-only JsonElement-based API over the top of that. So we can get the root element. That comes back as a JsonElement, so one of these very efficient things, but then I've wrapped it in this type here.
So I've got a static class called Gen... sorry, a namespace called GenFromJsonSchema, dot PersonArray.FromJson. It's going to give me this thing here, which is also a struct. It's kind of like a JsonElement, but it knows more about what's going to be in there. So this offers an EnumerateArray just like JsonElement does, but if I mouse over the lambda argument here, notice that the argument of the lambda is not just any old JsonElement. It's actually passing me a Person. So this array enumerator knows that this is not any old array, this is the person array, and each of the elements in it is a person. And these are still all structs, and these are still basically wrappers around JsonElements, so these are all very low allocation. So I'm able to enumerate the entire array and use LINQ to Objects over this to find the thing I want.
Now here's the really interesting thing about this. This uses the same basic structure as the very first benchmark I showed you, this not very clever one up here that reads the entire... sorry, the entire JSON in as one big array and then uses LINQ to Objects over it. If I come back to this latest example, it's basically doing the same thing, saying load the JSON, get the whole thing, and there's one big person array, and then use LINQ to Objects over that to get the results. But look at the results in the benchmark, and I promise you these are real. If I had time to run them you'd see the same results. That's that third up from the bottom, find whole array LINQ schema gen deserialize. It's almost 10 times faster than the first one. It doesn't have those garbage collection problems that the other ones did.
And we can do the kind of per element stuff, but actually there's much less benefit to doing that now. It turns out that with these wrappers we can do the stupid thing and magically it goes faster. How on earth is that working? Well, let's talk about that. So the way this works is that these generated types I'm showing you, and I'll show you the website that offers the tool to build these in a moment, these generated types look on the face of it like normal .NET objects. Let me just quickly go back and show you the benchmark again, because I kind of went over that quite quickly.
These benchmarks are able to do thing.Name.GivenName, like it was an ordinary deserialized object. They're able to do this, but we don't see those bad memory allocation characteristics. This whole thing ran with very low total memory allocation. If I go back up, 350 bytes, most of which was LINQ's fault. So this is working because these things are just facades over the data, exactly the same as JsonElements. They're not really deserializing anything. They're just sort of things saying, I'm this range of characters from here to here, I'm this range of characters from here to here. It's exactly the same sort of picture you saw earlier, but we've just stuck an extra layer on top of the JsonElements. These things are just wrappers for JsonElements that annotate them with properties that give you a way of accessing those underlying things.
Inside the generated code
And I'll quickly... I'm getting close to the end, but I'll quickly show you one example of that. So if I go looking at this name property, it's on this generated code, so it's a little bit of a mess. But this thing says, okay, well, actually you can run in one of two modes. These are actually writable things. You can either build a person by parsing some JSON, or you can actually build one out from scratch. The first thing it does, it says, am I made out of JSON or am I actually made out of values? And it has two completely different code paths.
If it says I'm made out of JSON, I'm actually just a wrapper for a JsonElement, it first of all says, well, is this the right kind of storage? Is this actually an object under here, or have you got the wrong sort of thing entirely? But if it is the right sort of thing, then it calls that same method our earlier benchmark did, TryGetProperty. It's saying, okay, it's calling JsonElement.TryGetProperty for the name it's expecting. So that is actually basically the property name. It's represented as a span, but it's basically the property name. And if that works then that will get a JsonElement out, and it will wrap that in another generated type, PersonName.
So these things are all basically just wrappers around JsonElements. It's kind of complicated because it's generated code, but fundamentally it's just this picture here. It's a generated layer sitting on top of the thing you already saw earlier. The generation, by the way, is driven by JSON Schema. That's how we know what to generate. So this only works for schematized data. But by the way, it supports validation. So if you do a JSON Schema, not only can we generate the wrappers for it, it'll also generate the code to validate that your JSON data is actually conforming to the schema, so you can be confident that it looks exactly like it should do. So there we are, I just showed you that.
Conclusion
So in conclusion, System.Text.Json can do serialization just like Newtonsoft.Json, Json.NET, but it's just faster out the box. If you do like for like code, it will be faster, mainly because it doesn't have to do any UTF-8 to UTF-16 conversion, but also generally within the code base they've had a lot more attention to avoiding unnecessary allocations. But if you're prepared to use the new JsonElement API, I say new, it's been here since .NET 5, the newish JsonElement API, directly, then this gives you an API that gives you very, very low allocation parsing at extremely high performance.
You can go faster still. Utf8JsonReader and Utf8JsonWriter give you ultra high performance, very low level access to the structure of the JSON, but that's the way to get the fastest performance. That can potentially go twice as fast again, but it's really hard work. There's built-in code generation for avoiding the use of reflection during serialization, and it's also possible to use a tactic of code generation to boost performance further without throwing away the benefits of serialization like behavior.
I'm going to quickly show you the website that that's on. So Corvus.NET is an open source library maintained by my employers, endjin. This is all free to use. You'll see the license when I go to the thing. So Corvus.JsonSchema is under the Apache 2 license, which is pretty permissive, and the instructions here will tell you how to use the tool that generates all those types that I showed you. So if you would like to use this, it's available. It's up there on GitHub, please have fun. But in any case, everything else I showed is built into .NET itself. So that is how we do high performance JSON processing in .NET. Thank you for listening.
Q&A: environmental impact
Matt: Oh, there we go. Oh, that was fantastic, thank you for that. We're pressing all the wrong buttons backstage here.
Ian Griffiths: Yeah, I was speaking into a dead microphone for the last 45 minutes.
Matt: Yeah. Ian, stop, stop. No, no, no, we've all been listening here and it's been fantastic. It's quite astonishing how much of an impact all of these techniques can have, and it's nice to see computers be really fast. Yeah, you hear so much about computers being so slow again these days, but it's nice to be able to get it really fast. So nice one, yeah, love it.
Ian Griffiths: Yeah, and there's actually... yeah, there's also... no, no, go ahead, go ahead. Environmental impact to all of this, right? You know, the amount of CPU time you consume doing stuff has a direct impact on carbon. You know, every CPU cycle you save, that's a bit less impact on the environment. So, and that's the thing at endjin we spend quite a lot of effort on. We've actually developed other high performance processing libraries in a similar vein. So we produce a library called AIS.NET that parses the radio messages that are sent by ships to report GPS data, and this was for a customer who was processing enormous volumes of that, and we were able to get a server farm from about 10 servers down to one by using more efficient methods. And that, yeah, that's pure power saving there. It makes a big difference, these techniques.
Matt: Yeah, that's pretty cool. And it's always nice with reflection, where you've kind of, you know, this stuff up front, because your assemblies aren't going to change for the lifetime of the application, for the deployment, but it's being generated every single time. So it makes sense to kind of get that information up front. Khalid, I think you had a question to go with.
Q&A: thinking about bits, bytes and copies
Khalid: Yeah, it's kind of interesting. I think Ian maybe alluded to the story behind it, but when you were going through the UTF-8 and UTF-16 encoding examples, I was like, well, duh, yeah, that makes total sense. But then I thought to myself, like, what was the story behind that, and like that discovery for you? Like, yes, this makes a lot of sense, but when you're dealing with .NET APIs that stuff isn't so evident when you're using just C#, you know, method calls and stuff like that.
Ian Griffiths: So you're asking how did I kind of make the connection that these sort of differences exist? Okay, yes. So I mean, the short answer is I'm really old. So I'm turning 50 in a couple of weeks. So as I mentioned, I first started using computers back at school in the 1980s, and so back then you kind of had to know what all the bits and bytes were doing. You only had, you know, a 64 kilobyte address space, and you could know most of what most of the bytes in memory were for in your head back then. And if you didn't, you wouldn't be able to fit anything of value inside a machine that small. And so I kind of come from a background of thinking about trying to cram a pint into a quart pot, so to speak.
And then my first job was actually writing kernel mode device drivers, so that's another thing where you really had to think about what is actually happening at the hardware level. Because there, if you want to get high performance, you need to think about things like how many times is the data being copied? Can we get this incoming data to go exactly where it needs to be? Because that's actually quite challenging. You know, you think of a server sitting there on the network, and suddenly some, you know, electrical signals start wiggling up and down on the network port. How does it know which of the, you know, 400 processes running on your machine is supposed to receive that data?
And if it can't work it out fast enough, it's going to have to put the data somewhere else while it works out where it's going, and then copy it into the place it needed to be. Whereas if you get it right, you can devise things in such a way that you don't make additional copies. And that directly connects to what I've been talking about here, because the single biggest thing about performance for this sort of processing is not making additional copies of your data. That's the number one thing. You know, if you learn nothing else, don't make copies.
And okay, I'm going to plug my book here because it's also relevant to the talk. So I write Programming C# for O'Reilly. The final chapter in that book is dedicated to these sorts of programming techniques. We have a whole chapter on memory efficiency measures in C#. We talk about Span and Memory and the pipeline reader and all that sort of stuff, and this is all part of that world in essence. And I show an example of high performance JSON parsing in that. And it's don't make copies. That's the single most important message of that whole chapter, is don't make unnecessary copies of your data, because that above anything else is what will kill you.
Because from a device driver point of view, it's like, well, the bus that connects your memory to your CPU can only do so many cycles per second, and if you make it do more things than necessary you're going to max out the capacity. It's as simple as that. But it's because I'm used to thinking, you know, at that level of hardware, because I've had to debug problems by putting probes onto the motherboard and trying to, you know, measure things on oscilloscopes. You know, you have to think in those terms.
Matt: And so somebody on the chat has just described you as coming... well, me too, because I'm of the same age. It's coming from the Clive Sinclair generation.
Ian Griffiths: Oh yes, absolutely, yes.
Khalid: When I was younger. No clue what that means.
Matt: Oh, for God... thank you. They were branded as... in the US, Timex was the rebranding of Sinclair.
Khalid: But yeah, they were not... it still does in the US. Okay, Boomers, that's all I can say.
Ian Griffiths: It was 45 servers down to one. I said about 30. It was more, it's four... they had 45 servers, reduced it to one.
Matt: That was very impressive. So that shows what a big impact this sort of thing can have, which is even better than the BenchmarkDotNet figures really.
Ian Griffiths: Yeah, I mean, that was applying a load of multiple techniques, but yes, it's all part of a package.
Q&A: code samples and where to find Ian
Matt: Yep. You know, an obvious question is, are these code samples available on GitHub? So yeah, are they available for the audience to get access to?
Ian Griffiths: All of the code gen stuff I showed at the end is up there, and that was the link I put there, and someone has reshared that link in... we'll share that link in the comments. So the demos are currently not available. The reason for that was that I was doing this talk at a bunch of conferences and didn't want to put it available for... I would end up making it available to people who haven't paid, who were going to go to a conference later. So yeah, I probably could do that now though. They're on a repo which is not currently public, but yeah, I can set that public now, I think.
Matt: Yeah, that'd be cool. We've been asked...
Ian Griffiths: Yeah, and I guess people can follow me. Okay, good.
Matt: I think we've got a delay. Khalid, why don't you go, go ahead.
Khalid: Well, I was just going to ask, folks should just follow Ian Griffiths on his social media channels, go to endjin. Maybe you'll end up writing a blog post there about this talk.
Ian Griffiths: So, yeah, and endjin is... yeah, the endjin blog's the best place. I am idg10 in most places. idg10 is me on GitHub, it's me on Twitter. I've been a lot less active lately on Twitter because reasons, but yeah, I'm... so sorry, Matt.
Q&A: customizing the generated JsonTypeInfo
Matt: Yeah, no, no problem. I was just gonna ask a different question. So we've been asked, I'm not quite sure what they're going to say, but can we add our own JSON property info arrays into the partial class that's getting generated? So if you wanted to override, or, you know, sort of have custom handling for what the code generator produces, is that possible?
Ian Griffiths: Right, so if I understand the question, the idea is that... sorry, someone said "Twitter question mark X", I should have said X. But anyway, back to your question. So the thing about that code gen is that it's creating a type called JsonTypeInfo<T>, which is almost entirely opaque, so its innards are not accessible to you. And so it's a sort of in only API, and it's not really meant for public deconstruction, so you certainly can't get any of the information back out of it yourself. So all of the generated code just pushes information in to what looks like a black hole, and to the best of my knowledge you can't really change that.
The only thing you could do would be to disable it entirely, copy what the code gen had done and then write your own version of it. So you could do that, because obviously the code gen can't do anything you couldn't write by hand, but there's no mechanism in the tooling, as far as I know, for getting it to do most of the work but for you to change a bit of it. I don't think they support that.
Q&A: generated code for deserialization
Matt: Yeah, yeah, and it all depends on what the original asker was intending to do with that additional property. I think we've got one last question before we wrap up then.
Khalid: At least again with the code generators there, you showed that it's kind of caching some reflection data to prevent that sort of first warm-up cost, and then also a serializer, wasn't it? Does it do anything at all for deserializing, or is that not appropriate?
Ian Griffiths: Oh no, it works in both directions, because serialization and deserialization both need the same information. Fundamentally they need to know what properties are there, and so they both use the same thing if you're using the JsonTypeInfo<T> stuff. However, if we're talking about the streaming stuff, so there was the code that basically does a very fast write out to the Utf8JsonWriter, I think it's called, yeah, there is no reader in that one. That's asymmetrical.
And the reason it's asymmetrical is, well, do you remember the code I showed you for the fastest one? That was, you know, eight pages of code. It's hard to write that stuff. But the more subtle aspect of it is that it's not at all clear what the output format should be. So that particular thing knew exactly what it was looking for and is returning a single thing once it's found it, but that's a very specific goal, and they could write a code gen that did that. But what if you wanted something else? What if you wanted the top three things? What if you wanted to group stuff? You'd need a different code gen every time.
And no one has yet proposed, within Microsoft or on Microsoft repos, how that might look in a way that looks plausible and sufficiently general for them to do it. I think they would like to do it. They said they would like to, but they said they don't have a design they consider good enough. Yeah, that's why they haven't done it.
Matt: Fair enough, that's good. Okay, well then, I think we're done. Thank you very much for your session. It's very interesting, lots of cool tips and useful things to know there. I'm sure a lot of people will put that into practice and benefit a lot from it. So thank you very much.
Ian Griffiths: Thank you.