К основному контенту

Unity C# Dictionary vs List

Поскольку Dictionary без велосипедов не сериализуется в Unity3D, я решил протестировать а стоит ли вообще использовать. Выше ли производительность?

Unity Version 4.6.1f1


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

[System.Serializable]
public class SomeData
{
    public string name;
    public Vector3 position;
    public Vector3 rotation;
    public string key;
    public string about;
    public int dataID;

    public SomeData(string name, Vector3 position, Vector3 rotation, string key, string about, int dataID)
    {
        this.name = name;
        this.position = position;
        this.rotation = rotation;
        this.key = key;
        this.about = about;
        this.dataID = dataID;
    }
}

public class DirListTest : MonoBehaviour
{
    private List<SomeData> list = new List<SomeData>();
    private Dictionary<string, SomeData> dict = new Dictionary<string, SomeData>();
    private Stopwatch stopWatch = new Stopwatch();
    private int count = 100000;

    private void Awake()
    {
        int i;

        for (i = 0; i < count; ++i)
        {
            SomeData data = new SomeData(
                i.ToString("#000000"),
                Vector3.one,
                Vector3.zero,
                i.ToString(),
                string.Empty,
                i
                );
            list.Add(data);

            dict.Add(data.name, data);
        }

        StartCoroutine(Test());
    }

    IEnumerator Test()
    {
        yield return new WaitForSeconds(2f);

        int i;
        string search;
        SomeData data;

        stopWatch.Reset();
        stopWatch.Start();
        for (i = count - 1; i >= 0; --i)
        {
            search = i.ToString("#000000");
            if (dict.ContainsKey(search))
            {
                data = dict[search];
            }
        }
        stopWatch.Stop();
        UnityEngine.Debug.Log("Dictionary search time: " + stopWatch.ElapsedMilliseconds.ToString());

        stopWatch.Reset();
        stopWatch.Start();
        for (i = count - 1; i >= 0; --i)
        {
            search = i.ToString("#000000");
            if (search.CompareTo(list[i].name) == 0)
            {
                data = list[i];
            }
        }
        stopWatch.Stop();
        UnityEngine.Debug.Log("List search time: " + stopWatch.ElapsedMilliseconds.ToString());

    }
}

Результаты:
Количество: 100000
Dictionary search time: 437
List search time: 555

Количество: 10000
Dictionary search time: 35
List search time: 56

Количество: 10
Dictionary search time: 0
List search time: 0

Комментарии