I’m concerned of people always using getter-setter pattern:
public int MyVariable { get; private set; }
public void SomeFunction(){
MyVariable = 10;
}
Which as far as I understand compiles to something like:
private int myVariable;
public int GetMyVariable(){
return myVariable;
}
private void SetMyVariable(int value){
myVariable = value;
}
public void SomeFunction()
{
SetMyVariable(10);
}
Doesn’t it impact the program’s performance if used frequently? Isn’t it better to do like that:
private int myVariable;
public int MyVariable { get {return myVariable; } }
public void SomeFunction(){
myVariable = 10;
}
First off, this type of optimization is typically counter productive – trying to optimize out single method calls is something that will typically have no impact in any real world, measured performance. You’re likely better off focusing your efforts on optimizing the algorithms you use at a higher level, and not micro-optimizing the language features used.
No. This will be effectively the same once compiled.
In addition, in a release build, the JIT compiler will typically completely optimize away the get and set methods, inlining them completely. This will effectively make it perform exactly like using a public field, and have the same performance as a direct member access.