40% faster JSON serialization with Source Generators in .NET 6

  Рет қаралды 72,243

Nick Chapsas

Nick Chapsas

Күн бұрын

Пікірлер: 94
@thehuggz-i9k
@thehuggz-i9k 3 жыл бұрын
I mean... when the IDE suggests Nick Cage, you use Nick Cage.
@fakhrulhilal
@fakhrulhilal 3 жыл бұрын
Please submit your name to MS, to see your name in suggestion list in the future 😆
@kblyr
@kblyr 3 жыл бұрын
Someone: How did you become better at software development? Me: I've been watching KZbin videos from Nick Cage
@NotInventedHereShow
@NotInventedHereShow 3 жыл бұрын
Last time I looked at the STJ source generator it actually only generated custom serialization for serialization, not for deserialization, so that matches your results.
@dominicc1804
@dominicc1804 3 жыл бұрын
Nice! Do you know if this will be integrated into the automatic de/serialisation for web API? I'm sure there are opportunities to improve this so that we can associate the serialisation context with its respective class to eliminate the need to provide the type in every endpoint. I would assume it could be done with a tiny config in the startup/builder coupled with naming conventions.
@dondumitru7093
@dondumitru7093 3 жыл бұрын
Excellent presentation in your video. Moved very quickly, and still easy to follow.
@Gioandgoose
@Gioandgoose 2 жыл бұрын
Great work and great way to dumb it down for us! Thank you I am now a subscriber.
@Gioandgoose
@Gioandgoose 2 жыл бұрын
By the way for context, I had a method taking 12-14 seconds, huge payload, down to 2 seconds so now to optimize the remaining code. Literally gona make me look so good at work lol
@WhitbyStuff
@WhitbyStuff 2 жыл бұрын
I recommend putting on captions with the mix of that accent and speed of talking.
@mr_sweez
@mr_sweez 3 жыл бұрын
Nice video! How does this work when serializing/deserializing dictionaries?
@uccc2282
@uccc2282 3 жыл бұрын
Nice video as always... did u try with a very long json? I wonder if the benchmark improves with less reflection in a class with a lot of properties
@flamendless
@flamendless 3 жыл бұрын
Nice video! Im just curious, but why make another class (PersonJsonContext) instead of just using serialize, wouldn't that be more typing and more files to manage?
@nickchapsas
@nickchapsas 3 жыл бұрын
Because you have to in order for the source generator to kick in and generate the class needed
@twiksify
@twiksify 3 жыл бұрын
Source generators can only add, not modify existing code. Thus a partial class is required to hook in the auto generated code.
@divinelemur9530
@divinelemur9530 2 жыл бұрын
I was gonna leave a like at the end of the video regardless but that Nick Cage autocomplete suggestion took me out. I left a like right then. Lmao!
@JustinMinnaar
@JustinMinnaar 2 жыл бұрын
I noticed on my own project that adding this immediately failed the project. The List that was serialized previously suddenly stopped working. I'll have to investigate later why.
@sajagjain7169
@sajagjain7169 3 жыл бұрын
Can this be wired with dotnet core mvc AddJsonOptions?
@rdwz9649
@rdwz9649 3 жыл бұрын
This serializes at compile time, so I don't think this is an option for MVC or webapi.
@Dokug
@Dokug Жыл бұрын
Hi Nick, do you know how to get the source generated serializer to accept and work with double.NaN values? I have spent some time researching it but, at least for me, setting JsonNumberHandling.AllowNamedFloatingPointLiterals does not work with the source generated JSON context..
@avocadopeel7536
@avocadopeel7536 3 жыл бұрын
#1 thing i learned from this video: TOP LEVEL STATEMENTS OH MY GOD WHEN DID C# ADD THIS YEEEEEES
@JensStragier
@JensStragier 3 жыл бұрын
Was added in C# 9 i believe!
@MatthewHudson
@MatthewHudson Жыл бұрын
Can this be made into a more generic method - more classes can be added to the context, but what if we want to pass any object into this method, could it find the type and utilise the correct jsontypeinfo for serialisation , pass this data with it and use this for the deserialisation...?
@binarybang
@binarybang 3 жыл бұрын
How does this work for complex types? Would I have to write a JsonContext for every complex property of that Person class (say, an "Address" property) or is this handled automatically?
@nickchapsas
@nickchapsas 3 жыл бұрын
Yeah it will handle it
@luls9000
@luls9000 2 жыл бұрын
can i generate .cs source code files from json or would that be stupid? for example a dictionary containing json key and value pairs
@walterhafner2910
@walterhafner2910 2 жыл бұрын
Hey im not so experienced in C# so sorry if it's a dumb question. but what is the best way of creating/ generating a Class from a given json ? are there source generators like this only for the opposite direction?
@reikooters
@reikooters 2 жыл бұрын
I know this is an older video and comment, but simply copy a sample json object to the clipboard, then open a new file in visual studio. Edit > Paste Special > Paste JSON as Classes. Sometimes you might need to modify the code that gets produced a bit (e.g. if it detects something as int but you know should be a long) but it will get you 95% of the way there. Properties that never have a value (always null) in your sample json it will use "object" as the type, so you'll need to fix those to the correct type.
@BernhardHofmann
@BernhardHofmann 2 жыл бұрын
Is this in a repo we can play with? I'd like to see how a `ToJson` method on the class would perform compared to the converters. For simple classes, and when you know the values won't contain JSON characters, it might be the fastest. Risky, but fast.
@sps014
@sps014 3 жыл бұрын
Looks like in few upcoming .net releases we will reach Serde-Json level in terms of performance
@lordicemaniac
@lordicemaniac 3 жыл бұрын
Interesting stuff as usually, love your videos. Btw, can you setup some converters or other things with this method like you normally do with attributes on properties?
@KeondreLucas
@KeondreLucas 3 ай бұрын
If there are multiple errors during serialization I want to return all of them to the client what's the best way to do this?
@minihopp123
@minihopp123 3 жыл бұрын
I have looked at some of your videos, but what IDE are you using?
@fyreek2569
@fyreek2569 3 жыл бұрын
Jetbrains Rider
@TheBadspeed
@TheBadspeed 3 жыл бұрын
Whats better? This or Newtonsoft deserialization/Serialization?
@nickchapsas
@nickchapsas 3 жыл бұрын
This is faster and more memory efficient but has less features. depends of how much of the advanced features of Newtonsoft you're using
@Joxel
@Joxel 3 жыл бұрын
Great video! Well explained and easy to follow.
@tarasbuha7726
@tarasbuha7726 3 жыл бұрын
Do you have any differences with Newtonsoft deserialisation?
@nickchapsas
@nickchapsas 3 жыл бұрын
Newtonsoft is just significantly slower than both approaches
@realrs123
@realrs123 3 жыл бұрын
Nice one! You should run benchmark only with release mode, could you try if you spot the difference?
@nickchapsas
@nickchapsas 3 жыл бұрын
It was in release mode. BenchmarkDotNet cannot run on Debug mode. All the benchmarks in all my videos are release mode.
@jamesmelvin3071
@jamesmelvin3071 3 жыл бұрын
Till you make your class partial (We leverage builder patterns created with a source generate. Seems partial isn't supported yet.
@zirkzirk1512
@zirkzirk1512 3 жыл бұрын
Can I get this to work with serializing the response in asp net core api calls? I'm interested in optimizing that
@cdarrigo
@cdarrigo 3 жыл бұрын
I wonder if this can be used for more than just Json serialization. can we use these compile time source code generation for things like mapping? It would be great to replace the automapper functionality of runtime reflection with generated mapping code. I would be really interested to see how that performed against the way we handle mapping today
@nickchapsas
@nickchapsas 3 жыл бұрын
Ofc. I've already covered this topic in this channel in the source generators video
@dondumitru7093
@dondumitru7093 3 жыл бұрын
Source generators are extremely powerful, but also somewhat involved to author. So if you have a strong custom use-case, you can invest the time and potentially get great or even results. But most developers will end up using source generators that are either provided out-of-box or from some other group of people who put the focus in to develop one for some specific use-case, because most developers are honestly not going to see the payback of investing in learning how to write source generators.
@KunalMukherjee3701
@KunalMukherjee3701 3 жыл бұрын
Writing the personjsoncontext class becomes redundant and verbose if we are serializing for multiple classes
@nickchapsas
@nickchapsas 3 жыл бұрын
A small price to pay for faster code
@ShootyMcStabbington
@ShootyMcStabbington 3 жыл бұрын
@@nickchapsas Not a bad idea for an IDE extension. A refactoring that can create the jsoncontext.{ext} file and class.
@giboco
@giboco 3 жыл бұрын
I would like to move to this, however, the lack of the required attribute has been holding me back, does anyone know if this has this been addressed yet? Or is there an alternative way to do this?
@normanbates9643
@normanbates9643 3 жыл бұрын
I'm new to C#. What is the default! in the Person class doing?
@GumbootMan
@GumbootMan 3 жыл бұрын
"default" represents the default value, which for strings is "null". The exclamation mark (!) says ignore any nullability warnings. So "string = default!" is basically saying, give me a non-nullable string property, and assign null to it, but don't warn me about assigning null to a non-null variable. It's a quick and dirty way of suppressing nullability warnings while keeping some of the benefits.
@misha130
@misha130 3 жыл бұрын
Why can't this be done with AOT instead? It seems odd to write JsonContext for each class that needs to be serialized
@nickchapsas
@nickchapsas 3 жыл бұрын
You don’t need a new context. Simply have one context and use multiple Types on it
@dannygorrilla
@dannygorrilla 3 жыл бұрын
Would this work with the Refit library?
@Miggleness
@Miggleness 3 жыл бұрын
i should update my json benchmark comparing bcl’s against the likes of utf8json and spanjson
@nvnYT26
@nvnYT26 3 жыл бұрын
can you please share the sample code used in the tutorial.
@hiwiscifi997
@hiwiscifi997 2 жыл бұрын
First of all: great video. *But* although it works just fine i do have a small issue in Visual Sudio when using this. It displays Errors since i didn't add a constructor etc. to the JsonContext class. It compiles just fine (The errors only show during editing...). Does anyone know how to suppress them? (Using VisualStudio Community 2022 with ReSharper) EDIT: The "partial" in the class declaration is also greyed out
@Ajay-km8br
@Ajay-km8br 3 жыл бұрын
Niceeee
@Max_Jacoby
@Max_Jacoby 3 жыл бұрын
Co-pilot must've been a second pilot in Con Air.
@MalClarke
@MalClarke Жыл бұрын
Why would we want to do this? What am I missing?
@theodorosdoukoulos9310
@theodorosdoukoulos9310 3 жыл бұрын
wow wow wow
@DarkF1nger
@DarkF1nger 2 жыл бұрын
I do not know C# is supported by copilot
@vertxxyz
@vertxxyz 3 жыл бұрын
I can't get this to work with my .net 6 project, and I'm wondering what I could be doing wrong. I save and I presume it's not running the generator. Is there a package or setting I might be missing (using Rider EAP 6)
@sadasdasdsadas1
@sadasdasdsadas1 2 жыл бұрын
have you figured out how to get over the error you had?
@befkotze
@befkotze 3 жыл бұрын
It is (1/0.62 - 1) = 61% faster. Really impressive! Thanks for sharing Nick.
@igorproskochilo9805
@igorproskochilo9805 3 жыл бұрын
Wtf 🤯
@mark7166
@mark7166 3 жыл бұрын
Nope.... if it's 62% of the original execution time, it's 38% faster.
@payamism
@payamism 3 жыл бұрын
Ok, but this was a linear serialization and deserialization. I am more interested to see how a complicated multi-nested JSON object is going to perform in your test.
@nickchapsas
@nickchapsas 3 жыл бұрын
The more complicated the usecase the faster the source gen will be
@mac9219
@mac9219 2 жыл бұрын
For me it doesn't give performance improvement. Also i have the question: how to use that in asp .net core api application?
@nickchapsas
@nickchapsas 2 жыл бұрын
You can use the context in the json setup of MVC, but you can only register one so you have to merge all your converters in one
@owns3
@owns3 2 жыл бұрын
I don't like the content... I love it!
@brunoccs
@brunoccs 3 жыл бұрын
"Hello everybody I'm nangandan..."
@muhamedkarajic
@muhamedkarajic 3 жыл бұрын
As always really informative. Wondering if that's possible for XML?
@АйнурМингалиев-ы1з
@АйнурМингалиев-ы1з 2 жыл бұрын
it's not works with Generic types(
@mehmetck
@mehmetck 3 жыл бұрын
Still SpanJson faster then .net 6 Codegen version
@Kokujou5
@Kokujou5 2 жыл бұрын
yeiiii... so all we need to do is create an additional class for all the DTOs in our service that need serialization? well... thank ... you? i mean i think i'd rather wait the additional years until this code becomes default because i would rather not have dozens of garbage classes with no actual coding-purpose lying around in my code XD but maybe one can build those things with your solution in the swagger context. like iterate through all models in your swagger response/request documentation and generat a default serializer for all of them. however if you consider how fast Json serialization already is, the few miliseconds we save here are not really worth the effort. maybe it's worth a thought if you deal with megabytes of mass data. if you really want to speed controller responses up, then i'd suggest you take a look at returning iqueryable directly from your controller. if you now find a way on how i can actually catch serialization errors that happen while serializing an EFCore iqueryable, then you are king
@Ris-v4w
@Ris-v4w Жыл бұрын
what if your person's name is Json ? 😶 doesn't the default way of serializing go 40% faster already?
@aegis_helion
@aegis_helion 3 жыл бұрын
Jil library still beats Microsoft heavily...
@ahmetfatihsalim7616
@ahmetfatihsalim7616 2 жыл бұрын
This video is like "How to draw owl: Step 1 : draw 2 circles, Step 2 : draw the rest of the fucking owl" meme type of video. Like, in order to understand whats happening, you need to have a bit of background. Otherwise you will just stare the 2 circles you draw which supposed to be a fucking owl.
@jjxtra
@jjxtra 3 жыл бұрын
0.69 eh?...
@oldfish3059
@oldfish3059 3 жыл бұрын
my Patreon account has been disabled,Are there any other visits to get source code access?
@jacobstamm
@jacobstamm 2 жыл бұрын
Nick Cage lmao
@mahesh_rcb
@mahesh_rcb 3 жыл бұрын
Code writing code ...nioceee 😅
@nested9301
@nested9301 3 жыл бұрын
dude c sharp syntax is just way to hard
@jackoberto01
@jackoberto01 3 жыл бұрын
Compared to what other language? Imo it's one of the most readable languages and flows very well
The Fix For Your Database Performance Issues in .NET
9:12
Nick Chapsas
Рет қаралды 66 М.
Don't throw exceptions in C#. Do this instead
18:13
Nick Chapsas
Рет қаралды 263 М.
Creative Justice at the Checkout: Bananas and Eggs Showdown #shorts
00:18
Fabiosa Best Lifehacks
Рет қаралды 33 МЛН
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 14 МЛН
Одну кружечку 😂❤️
00:12
Денис Кукояка
Рет қаралды 861 М.
Players push long pins through a cardboard box attempting to pop the balloon!
00:31
Роман Щербаков «C# 9.0 Source Generators»
24:31
8 await async mistakes that you SHOULD avoid in .NET
21:13
Nick Chapsas
Рет қаралды 315 М.
Writing C# without allocating ANY memory
19:36
Nick Chapsas
Рет қаралды 152 М.
When You Shouldn't Use Await Async in .NET
7:51
Nick Chapsas
Рет қаралды 37 М.
Фичи и производительность C#  11 .net 7 vs C# 10 .net 6
29:02
Архитектор ПО. Александр Желнин
Рет қаралды 12 М.
You are doing .NET logging wrong. Let's fix it
25:29
Nick Chapsas
Рет қаралды 174 М.
Fix Your Controllers By Refactoring To Minimal APIs
14:56
Milan Jovanović
Рет қаралды 44 М.
What are record types in C# and how they ACTUALLY work
15:36
Nick Chapsas
Рет қаралды 122 М.
How IEnumerable can kill your performance in C#
11:02
Nick Chapsas
Рет қаралды 119 М.
Creative Justice at the Checkout: Bananas and Eggs Showdown #shorts
00:18
Fabiosa Best Lifehacks
Рет қаралды 33 МЛН