「毎日Unity」の技術ブログ

開発で役立つ情報を発信する

【UnityC#】List.RemoveAt、LinkedList.RemoveFirst、HashSet.Remove、Dictionary.Removeの速度比較

List.RemoveAt、LinkedList.RemoveFirst、HashSet.Remove、Dictionary.Removeの速度比較をしたので結果を残しておきます。

[ 環境 ]

Unity 2018.4.14.f1

[ 比較結果 ]

List.RemoveAt 261 ms
LinkedList.RemoveFirst 5 ms
HashSet.Remove 2 ms
Dictionary.Remove 1 ms

[ スクリプト ]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PerformanceComparison : MonoBehaviour
{
    void Start()
    {
        System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch();

        int Count = 100000;

        List<int> List_ = new List<int>(){};
        LinkedList<int> LinkedList_ = new LinkedList<int>(){};
        HashSet<int> HashSet_ = new HashSet<int>(){};
        Dictionary<int, int> Dictionary_ = new Dictionary<int, int>(){};

        for(int i = 0; i < Count; i++)
        {
            List_.Add(i);
            LinkedList_.AddLast(i);
            HashSet_.Add(i);
            Dictionary_.Add(i, i);
        }

        //List

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            List_.RemoveAt(0);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //LinkedList

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            LinkedList_.RemoveFirst();
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //HashSet

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            HashSet_.Remove(i);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);

        //Dictionary

        StopWatch.Restart();

        for(int i = 0; i < Count; i++)
        {
            Dictionary_.Remove(i);
        }

        Debug.Log(StopWatch.ElapsedMilliseconds);
    }
}