Andy Andy - 1 year ago 59
C# Question

Boxing Memory concerns

private double _value;

public object Value
return _value;


Hi guys just doing code reviews and noticed this in our codebase. Its not a typo but my concerns are with the boxing that is involved when the getter is called and given that this code is in a type that is generated hundreds of times and the getter is called frequently I can see an issue with memory.

Are my concerns correct with memory? I mean are we doubling up due to the boxing?

Answer Source

Yes, the code snippet that you've shown will indeed cause boxing. You're forcing the run-time to convert a double into an object. If you want to prove it to yourself or a colleague, check the compiled IL for the tell-tale box and unbox instructions.

However, while you're correct in looking out to avoid boxing wherever possible, the actual performance penalty is not always as significant as the hype makes it out to be. Before making breaking changes to your codebase, invest some time profiling to make sure that the code you're spending your time on is really a performance bottleneck.

It's not particularly clear given the specific example above why you need to return type object in the first place. Since you're just returning the value of a private field, you could simply change the property to return type double, instead.

Alternatively, you could convert the property to a generic method. (Properties can't be generic, but methods can, and if you're doing computationally-intense work inside the getter, it probably should be a method anyway.) Generics alleviate the problem of boxing, but still allow you an immense degree of flexibility in what type is returned (similar to returning type object).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download