0

Is it possible to tell the deserializer (via e.g. ContractResolver) to write the value of a Property directly to its internal or private backing field instead of using its setter?

Model:

    public class TestModel
    {
        public string Name
        {
            get => _Name; 
            set
            {
                // do some very expensive stuff
                _Name = value;
            }
        }

        internal string _Name = string.Empty;
    }

So my expectation is, that after some magic code the Deserializer writes the value for Property "Name" to the field "_Name" and avoid the expensive extra work done in setter of the Name prop.

  • 1
    Sounds like a design problem if you have "some very expensive stuff" happening in a setter. You should think about moving that to a method. Or you could add another property that controls whether the "expensive stuff" occurs, like `IsDeserializing` that is set to true by default, but set to false along those paths where you need it to run (and have "expensive stuff" run when `IsDeserializing` is false). – Heretic Monkey Mar 29 '22 at 16:05
  • @HereticMonkey can I let the ContractResolver do that ? :P – user2292496 Mar 30 '22 at 07:29

1 Answers1

0

Firstly, how do you actually know that there is a performance difference in both approaches? And how do you know that this is significant enough to justify such optimisation?

If you look at this

https://www.jacksondunstan.com/articles/2968

and this

Performance overhead for properties in .NET

Then you can see that you are really trying to over optimise this, and you are basically not going to gain any performance. You will certainly not gain anything that is significantly noticeable by the end user.

If you are so concerned about performance, then you shouldn't be using JSON!

jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
  • The commend "// do some very expensive stuff" is a placeholder for actually happening code. I don't want to run this code when creating the Object with deserialization. – user2292496 Mar 29 '22 at 18:52