コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】Dictionary のキーに列挙型を使う時のパフォーマンスを測定

ソースコード

using System;
using System.Collections.Generic;
using NUnit.Framework;
using Unity.PerformanceTesting;

// Dictionary のキーに列挙型を使用する時のパフォーマンスを測定するクラス
public sealed class DictionaryEnumKeyTest
{
    // 検証用の列挙型
    private enum JobType
    {
        SOLDIER,
    }

    // Dictionary のキーに int を使用する時のパフォーマンスを測定
    [Test]
    [Performance]
    public void KeyIntTest()
    {
        var dictionary = new Dictionary<int, string>();
        var key        = 0;

        dictionary[ key ] = "";

        Run( () => dictionary.GetValueOrDefault( key ) );
    }

    // Dictionary のキーに列挙型を使用する時のパフォーマンスを測定
    [Test]
    [Performance]
    public void KeyEnumTest()
    {
        var dictionary = new Dictionary<JobType, string>();
        var key        = JobType.SOLDIER;

        dictionary[ key ] = "";

        Run( () => dictionary.GetValueOrDefault( key ) );
    }

    // 指定された処理を実行してパフォーマンスを測定
    private static void Run( Action action )
    {
        const int warmupCount              = 10;     // 測定を開始する前に実行する回数
        const int measurementCount         = 100;    // 測定数
        const int iterationsPerMeasurement = 100000; // 測定ごとのメソッドの実行回数

        Measure
            .Method( action )
            .WarmupCount( warmupCount )
            .MeasurementCount( measurementCount )
            .IterationsPerMeasurement( iterationsPerMeasurement )
            .GC()
            .Run()
            ;
    }
}

測定結果

列挙型

int

検証環境

  • Unity 2021.2.11f1