C#

値型のボックス化は高コスト

C#のパフォーマンス向上について調べていると以下のページを見つけた。
http://msdn2.microsoft.com/ja-jp/library/ms173196(VS.80).aspx

”ボックス化”の作業には非常にコストが掛かることが示されている。
ボックス化とは値型をオブジェクト型にキャストする操作のことで、その反対を”ボックス化解除”と言う。

この件に関して実際にコードを組んでパフォーマンスを測定してみた。


クラスと構造体について以下のC#のコードを記述して実行した。
ちなみにクラスをボックス化してもあまり意味が無い。

using System;
using System.Diagnostics;

class Program
{
    class reftype // クラスは参照型
    {
        public int a;
        public int b;
        public int c;
        public int d;
    }

    struct valtype // 構造体は値型
    {
        public int a;
        public int b;
        public int c;
        public int d;
    }

    static void Main()
    {
        const int roopCount = 10000000;
        reftype r = new reftype(); // 参照型
        valtype v = new valtype(); // 値型
        Stopwatch sw = new Stopwatch();

        // 参照型のボックス化&ボックス化解除
        sw.Reset();
        sw.Start();
        for (int i = 0; i < roopCount; i++)
        {
            object obj = (object)r;
            reftype ubr = (reftype)obj;
        }
        sw.Stop();
        Console.WriteLine("ReferenceType took {0} ms", sw.ElapsedMilliseconds);

        // 値型のボックス化&ボックス化解除
        sw.Reset();
        sw.Start();
        for (int i = 0; i < roopCount; i++)
        {
            object obj = (object)v;
            valtype ubv = (valtype)obj;
        }
        sw.Stop();
        Console.WriteLine("ValueType took {0} ms", sw.ElapsedMilliseconds);

        Console.ReadLine();
    }
}

実行結果は以下のようになった。

ReferenceType took 31msec
ValueType took 281msec

はっきりと10倍近いパフォーマンスの差が出た。
メンバ変数を増やすと値型の方はもっと遅くなる。

この違いは覚えておいて損はないかもしれない。

スポンサーリンク
管理人

システムえんじにゃー🐈
趣味はエレキギターなど。作曲したい。
WoWs/プリコネ
記事に関する質問はお気軽にどうぞ。

surface0 (さーふぇす)をフォローする
surface0 (さーふぇす)をフォローする

コメント

タイトルとURLをコピーしました