2010/05/30(Sun)最適化実験

はてブ数 2010/05/30 6:14 プログラミング::C# つーさ

暗黙的型変換の最適化に関する実験。

public struct A
{
    public A(int x, int y) { this.X = x; this.Y = y; }
    public int X, Y;
}

public struct B
{
    public B(int p1, int p2) { this.p1 = p1; this.p2 = p2; }
    public int p1, p2;

    public static implicit operator A(B b) { return new A(b.p1, b.p2); }
}

private int Calc(A a) { return a.X + a.Y; }

private void Test()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    for (int x = 0; x < 100; x++)
    {
        int count = 0;
        for (int i = 0; i < 10000000; i++)
        {
            count += Calc(new A(count, 1)); // これと
            count += Calc(new B(count, 1)); // これの違い?
        }
    }
    sw.Stop();
    MessageBox.Show((sw.ElapsedMilliseconds / 100).ToString()+"ms.");
}

実行時間

Debug: new A(...) → 544ms
Debug: new B(...) → 1129ms
Release: new A(...) → 28ms
Release: new B(...) → 28ms

struct A と Calc(...) が別のライブラリにある場合

Debug: new A(...) → 552ms
Debug: new B(...) → 1112ms
Release: new A(...) → 28ms
Release: new B(...) → 29ms

struct B も あっちの世界にある場合

Debug: new A(...) → 552ms
Debug: new B(...) → 1153ms
Release: new A(...) → 29ms
Release: new B(...) → 122ms

struct B が 第三国にある場合

Release: new B(...) → 122ms

結論

ちゃんと最適化される。
ただまぁ、結構誤差がきついかなぁ……