I have a property with a backing field and some logic inside the setter. I wonder whether I should use the value keyword or the backing field.
Option 1:
private bool _backingField;
public bool MyProperty
{
get => _backingField;
set
{
_backingField = value;
if(value) // <--
{
...
}
}
}
Option 2:
private bool _backingField;
public bool MyProperty
{
get => _backingField;
set
{
_backingField = value;
if(_backingField) // <--
{
...
}
}
}
Which of them has better performance? Tests I have run on my machine showed no significant difference, but I am not sure my machine is enough to get the whole picture.
Note: I do realize this is probably taking micro-optimization to a whole new level of ridiculousness, but I am still curious to know if there is a definitive answer.
Edit: This question is not opinion-based, since I am asking if there is an objective difference.
Here's the IL generated with
if(value)in Release mode:Note that I've added
Console.WriteLine("true");to the body of theifto prevent it to be removed by the compiler.Now the IL with
if (_backingField):The only difference is the additional call to
ldfld bool ConsoleApp1.Program::_backingFieldin the second version, so in theory it should be a tick slower. However, that tick should be negligible small.