Properties vs Fields – speed comparison
class X
{
private int _p1;
private int _p2;
public int P1
{
set => _p1 = value;
get => _p1;
}
public int P2
{
set => _p2 = value;
get => _p2;
}
public int A1 { set; get; }
public int A2 { set; get; }
public int F1;
public int F2;
}
class Program
{
static void Main(string[] args)
{
int N = 100_000_000;
X x = new X();
Stopwatch sw = new Stopwatch();
Console.ReadLine();
sw.Start();
for (int i = 0; i < N; i++)
{
x.P1++;
x.P2 = x.P1;
}
sw.Stop();
Console.WriteLine(x.P2 + " " + sw.Elapsed);
//output: 99999999 00:00:01.4351390
sw.Reset();
sw.Start();
for (int i = 0; i < N; i++)
{
x.A1++;
x.A2 = x.A1;
}
sw.Stop();
Console.WriteLine(x.A2 + " " + sw.Elapsed);
//output: 99999999 00:00:01.4296915
sw.Reset();
sw.Start();
for (int i = 0; i < N; i++)
{
x.F1++;
x.F2 = x.F1;
}
sw.Stop();
Console.WriteLine(x.F2 + " " + sw.Elapsed);
//output: 99999999 00:00:00.2331003
Console.ReadLine();
}
}