rksoftware

Visual Studio とか C# とかが好きです

フィールドとプロパティの速さ

ふと気になってフィールドとプロパティの速さを比べてみました。
かつて少し触っていた言語で、フィールドかアクセサメソッドかという議論でアクセサメソッドの方が速いという記事を見たこともあったので。
※速度は環境によって異なります。結果は一例です。

■ 結果

Total field : 10000000000 : 50752 ms
Total properties : 10000000000 : 47253 ms

値の設定と取得を 10,000,000,000 回行って 3,499 ミリ秒プロパティの方が速いという結果になりました。
1 回あたり 0.0000003499 ミリ秒の差です。どちらでも良いですね。
特にこだわりがなければ、誤差レベルで速いしプログラミングとしてエレガントだしプロパティで良さそうです。

■ コード

namespace Models
{
    public class Fields
    {
        public long MyField;
    }

    public class Properties
    {
        public long MyProperty { get; set; }
    }
}
namespace Methods
{
    public class Methods
    {
        public void Method(Fields fields) { fields.MyField += 1; }
        public void Method(Properties properties) { properties.MyProperty += 1; }
    }
}
namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var fieldsTime = 0L;
            var propertiesTime = 0L;
            var method = new Methods.Methods();
            var fields = new Fields();
            var properties = new Properties();
            foreach (var _ in Enumerable.Range(0, 1000))
            {
                fieldsTime += Measure(() => { foreach (var index in Enumerable.Range(0, 10000000)) method.Method(fields); });
                propertiesTime += Measure(() => { foreach (var index in Enumerable.Range(0, 10000000)) method.Method(properties); });
                Console.WriteLine($"field      : {fields.MyField} : {fieldsTime} ms");
                Console.WriteLine($"properties : {properties.MyProperty} : {propertiesTime} ms");
            }
            Console.WriteLine($"Total field      : {fields.MyField} : {fieldsTime} ms");
            Console.WriteLine($"Total properties : {properties.MyProperty} : {propertiesTime} ms");
            Console.ReadKey();
        }

        static long Measure(Action action)
        {
            var sw = Stopwatch.StartNew();
            action();
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }
    }
}