Alex Schmidt
Alex Schmidt

Reputation: 39

Why Property Access is Slower than Member access

I have been trying to optimize the performance of access to a time-critical class. When I measured, I was surprised to find a significant difference in performance between Member access and Property access. See example below:

using System;
using System.Diagnostics;

public class ClassSample {
    public static int StaticField = 0;
    public int InstanceMember = 0;
    public int PropertyField { get; set; }
    public ClassSample() {
        PropertyField = 0;
    }
}

public class Program {
    public static void Main(string[] arg) {
        var obj = new ClassSample();
        int N = 10000000;
        Stopwatch sp = new Stopwatch();
        sp.Start();
        int total = 0;
        for (int i = 0; i < N; i++) {
            ClassSample.StaticField = i;
            total += ClassSample.StaticField;
        }
        sp.Stop();
        Console.Out.WriteLine("Static  :\t" + sp.Elapsed);
        sp.Restart();

        total = 0;
        for (int i = 0; i < N; i++) {
            obj.InstanceMember = i;
            total += obj.InstanceMember;
        }
        sp.Stop();
        Console.Out.WriteLine("Member:  \t" + sp.Elapsed);
        sp.Restart();

        total = 0;
        for (int i = 0; i < N; i++) {
            obj.PropertyField = i;
            total += obj.PropertyField;
        }
        sp.Stop();
        Console.Out.WriteLine("Property:\t" + sp.Elapsed);
    }
}

Where I run this (.Net 4.5/Windows 10), I get these results:

Static  :       00:00:00.0243832
Member:         00:00:00.0240386 
Property:       00:00:00.0624915

So the Property access is more than twice slower than the others. Is this expected? Any way to avoid it?

Upvotes: 2

Views: 400

Answers (3)

Wazner
Wazner

Reputation: 3102

Properties are basically special methods. Calling a method has more overhead than reading the value of a field.

Did you build your performance test in Debug mode? When build in Release mode the compiler inlines trivial property getters/setters and should make properties perform roughly the same as fields.

Upvotes: 1

Djeurissen
Djeurissen

Reputation: 378

int Property{get; set;}

Is the same as

private int property; 
public int GetProperty(){...} 
public void SetProperty(int value){...}

I would guess that the method overhead makes it slower.

Upvotes: 0

Milton Hernandez
Milton Hernandez

Reputation: 664

I have experienced this as well, but I figured out later that, if you optimize your Release target properly, the Property access is optimized by the compiler to a point that it is equal in performance to the member access. Give it a try and run the Release target, you should see a marked improvement. It seems like most of the difference has to do mostly with running in Debug.

Upvotes: 4

Related Questions