High performances way to access members?

Hello, I'm developing a API for visiting members of a object and reading their values, for using in serialization, data validation, etc. I am trying to make it high performant (as reasonably possible), so I want to avoid boxing from reflection. So I've been using generics with MakeGenericMethod/Type with PropertyInfo and delegates to avoid it mostly. The issue is that it isn't well supported with Native AOT. So an alterative I thought of was to mark every class/record/struct with an attribute, and use source generation to make a 'handler' for it. But that feels like it would really bloat the class count along with compile times. Any recommendations, insights or alternatives?
10 Replies
canton7
canton72d ago
Ah, if you need to target NativeAOT, then things like run-time code generation won't work (which is what I'd reach for) The C# compiler is quick: I wouldn't worry too much about a few extra classes
MechWarrior99
MechWarrior99OP2d ago
Yeah that is what I would normally do as well. It would be 100s of extra classes. Or alternatively, assuming I understand the limitations of MakeGeneric with NativeAOT, I could have a big class with a method or something that calls/uses the generics I need for each class?
HtmlCompiler
HtmlCompiler2d ago
if sg would add 1 million lines of code then i would think twice before doing it, but even 100 K loc is not a big deal
MechWarrior99
MechWarrior99OP2d ago
Is it loc that make the difference or number of classes/structs?
HtmlCompiler
HtmlCompiler2d ago
i think you worry too much, anyway i doubt number of objects would make a difference
MechWarrior99
MechWarrior99OP2d ago
Well that makes me feel better, but it would still be a lot. Was hoping there might be a nicer way than to 'brute force' generate handlers for every object.
canton7
canton72d ago
The current advice for SGs is to only process objects marked with an attribute. The problem isn't compiling the generated code, but re-generating the code on every keystroke Look at e.g. how the System.Text.Json SG does it
MechWarrior99
MechWarrior99OP2d ago
Oh that makes sense. Yeah my thinking was to only process objects with an attribute. Good thinking to look at how System.Text.Json does it. Do you know if it makes a difference if all the generated code is in a single class/method vs a class-per type? No big deal if not, I can just do a bit ore reading on it, but figured it was worth asking.
canton7
canton72d ago
SGs are supposed to be incremental. As in, they just re-generate what they need on each keystroke, and cache the rest. Therefore, generating small bits of code is good, because you can re-generate a small bit and cache the rest
MechWarrior99
MechWarrior99OP2d ago
That makes sense, thanks

Did you find this page helpful?