Eigenschaften und Leistung nutzen

Ich habe meinen Code optimiert und festgestellt, dass die Verwendung von Eigenschaften (auch von automatischen Eigenschaften) einen erheblichen Einfluss auf die Ausführungszeit hat. Siehe folgendes Beispiel:

[Test]
public void GetterVsField()
{
    PropertyTest propertyTest = new PropertyTest();
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    propertyTest.LoopUsingCopy();
    Console.WriteLine("Using copy: " + stopwatch.ElapsedMilliseconds / 1000.0);

    stopwatch.Restart();
    propertyTest.LoopUsingGetter();
    Console.WriteLine("Using getter: " + stopwatch.ElapsedMilliseconds / 1000.0);
    stopwatch.Restart();
    propertyTest.LoopUsingField();
    Console.WriteLine("Using field: " + stopwatch.ElapsedMilliseconds / 1000.0);
}

public class PropertyTest
{
    public PropertyTest()
    {
        NumRepet = 100000000;
        _numRepet = NumRepet;
    }

    int NumRepet { get; set; }
    private int _numRepet;
    public int LoopUsingGetter()
    {
        int dummy = 314;
        for (int i = 0; i < NumRepet; i++)
        {
            dummy++;
        }
        return dummy;
    }

    public int LoopUsingCopy()
    {
        int numRepetCopy = NumRepet;
        int dummy = 314;
        for (int i = 0; i < numRepetCopy; i++)
        {
            dummy++;
        }
        return dummy;
    }

    public int LoopUsingField()
    {
        int dummy = 314;
        for (int i = 0; i < _numRepet; i++)
        {
            dummy++;
        }
        return dummy;
    }
}

ImRelease Modus auf meinem Computer bekomme ich:

Using copy: 0.029
Using getter: 0.054
Using field: 0.026 

Was in meinem Fall eine Katastrophe ist - die kritischste Schleife kann einfach keine Eigenschaften verwenden, wenn ich maximale Leistung erzielen möchte.

Was mache ich hier falsch? Ich dachte, dass dies sein würdeinlined bis zumJIT optimizer.

Antworten auf die Frage(5)

Ihre Antwort auf die Frage