Unity關于Dictionary的遍歷問題

在字典中我們會調用到循環(huán)遍歷,當我們用一個自定義字典然后里面存了有復數個數據結構,里面有Update更新方法我們就要在管理類調用,用foreach遍歷啟動每一個Update,當我們刪除字典其中一個的時候就會報錯。
因為foreach是個迭代器,循環(huán)時不能進行改動。
1.第一個解決方法用一個list在調用Update之前加進去

// 存儲所有打開的界面, key-界面名稱, value-窗口名稱
    private Dictionary<string, BaseWindow> _windows = new Dictionary<string, BaseWindow>();
    List<BaseWindow> windows = new List<BaseWindow>();

 public void Update(float dt)
    {
        //清空列表
        windows.Clear();
        foreach (BaseWindow wnd in _windows.Values)
        {
            if (wnd != null)
                windows.Add(wnd);
        }
        for (int i = 0; i < windows.Count; i++)
        {
            windows[i].Update(dt);
        }
    }

慎用消耗性能過大
2.用for循環(huán)遍歷字典

using System.Linq;

 for (int i = 0; i < _windows.Count; i++)
        {
           //i為當前字典第i個 即使是string也會有放入順序
            var item = _windows.ElementAt(i);
            Debug.Log(item.Value.ShowName);
            Debug.Log(item.Value.Name);
        }

3.用List 根據list[i]查找相當于字典的key為int不過用不了string
4.自己封裝字典 就是一個字典倆List對應

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
// 主要優(yōu)化foreach
public class GameMap<TKey, TValue>
{

    private Dictionary<TKey, TValue> m_Map = new Dictionary<TKey, TValue>();
    public GameMap()
    {
    }
    List<TKey> m_base_key = null;
    List<TValue> m_base_TValue = null;
    public int Count { set; get; }

    public void Add(TKey key, TValue value)
    {
        m_Map.Add(key, value);
        m_base_key = new List<TKey>(m_Map.Keys);
        m_base_TValue = new List<TValue>(m_Map.Values);
        Count = m_Map.Count;
    }


    public void AddOrReplace(TKey key, TValue value)
    {
        m_Map.Remove(key);
        m_Map.Add(key, value);
        m_base_key = new List<TKey>(m_Map.Keys);
        m_base_TValue = new List<TValue>(m_Map.Values);
        Count = m_Map.Count;
    }
    public void TryAdd(TKey key, TValue value)
    {
        if (getDataByKey(key) != null)
            return;


        m_Map.Add(key, value);
        m_base_key = new List<TKey>(m_Map.Keys);
        m_base_TValue = new List<TValue>(m_Map.Values);
        Count = m_Map.Count;
    }


    public bool Remove(TKey key)
    {
        bool ret = m_Map.Remove(key);
        m_base_key = new List<TKey>(m_Map.Keys);
        m_base_TValue = new List<TValue>(m_Map.Values);
        Count = m_Map.Count;
        return ret;
    }


    public TValue getDataByIndex(int index)
    {
        return m_base_TValue[index];
    }


    public TKey getKeyByIndex(int index)
    {
        return m_base_key[index];
    }
    public void Clear()
    {
        m_Map.Clear();
        if (m_base_key != null)
        {
            m_base_key.Clear();
        }
        if (m_base_TValue != null)
        {
            m_base_TValue.Clear();
        }

        Count = m_Map.Count;
    }

    public TValue getDataByKey(TKey key)
    {
        TValue _baseMsg;
        m_Map.TryGetValue(key, out _baseMsg);//  [key];

        return _baseMsg;

    }
    public bool TryGetValue(TKey key, out TValue _baseMsg)
    {
        return m_Map.TryGetValue(key, out _baseMsg);//  [key];

    }

    public bool ContainsKey(TKey key)
    {
        return m_Map.ContainsKey(key);//  [key];

    }
}

遍歷性能對比

using UnityEngine;
using System.Collections;
using System.Diagnostics;
using System;
using System.Linq;
using System.Collections.Generic;
public class TextDicSpeed : MonoBehaviour
{
    Dictionary<int, int> dic;
    GameMap<int, int> dic1;
    // Use this for initialization
    void Start()
    {
        dic = CreateArr(10000);
        dic1 = CreateArr1(10000);
        int k;
        int v;
        Stopwatch time = new Stopwatch();
        time.Start();
        //foreach (var item in dic) //時間為1
        //{
        //    k = item.Key;
        //    v = item.Value;
        //    if (k == 500)
        //    {
        //        //會報錯就先不移除了
        //        // dic.Remove(k);
        //    }
        //}

        //for (int i = 0; i < dic.Count; i++)//時間為4370
        //{
        //    var item = dic.ElementAt(i);
        //    k = item.Key;
        //    v = item.Value;
        //    if (k == 500)
        //    {
        //        dic.Remove(k);
        //    }
        //}

        for (int i = 0; i < dic1.Count; i++)//時間為3
        {

            k = dic1.getKeyByIndex(i);
            v = dic1.getDataByIndex(i);
            if (k == 500)
            {
                dic1.Remove(k);
            }
        }
        time.Stop();
        UnityEngine.Debug.Log(time.ElapsedMilliseconds);
    }
    /// <summary>
    /// 創(chuàng)建一個很大的Dic
    /// </summary>
    /// <param name="v"></param>
    /// <returns></returns>
    public static Dictionary<int, int> CreateArr(int v)
    {
        Dictionary<int, int> arr = new Dictionary<int, int>();
        System.Random r = new System.Random();
        for (int i = 0; i < v; i++)
        {
            arr.Add(i, r.Next(0, v));
        }
        return arr;
    }

    /// <summary>
    /// 創(chuàng)建一個很大的Dic1
    /// </summary>
    /// <param name="v"></param>
    /// <returns></returns>
    public static GameMap<int, int> CreateArr1(int v)
    {
        GameMap<int, int> arr = new GameMap<int, int>();
        System.Random r = new System.Random();
        for (int i = 0; i < v; i++)
        {
            arr.Add(i, r.Next(0, v));
        }
        return arr;
    }
}

可見用字典帶的for循環(huán)優(yōu)化賊吉爾差,幾千倍的差距在10000個遍歷下

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容