Unity中的Dictionary(字典)的遍历

来源:互联网 发布:人类进化史知乎 编辑:程序博客网 时间:2024/06/07 05:59

         很多关于unity优化的文章都说到,尽量用for做遍历,而不是用foreach做遍历。原因是foreach会产生更多GC。那如果是Dictionary呢?Dictionary不用foreach是绕不过去的(别告诉我转成一个List然后用for,这样绕远了,GC也不少)。其实foreach也有3种遍历方式,可以根据自己需求来用。还有一种不用foreach的方式,但我个人认为这样并不能减少GC.

1.Dictionary的四种遍历

(1)KeyValuePair

         这是最常见的一种

        Dictionary<string, int> dic = new Dictionary<string, int>();        dic.Add("a", 2);        dic.Add("b", 5);        dic.Add("c", 8);        foreach (KeyValuePair<string, int> pair in dic)        {            Debug.Log(pair.Key + " " + pair.Value);        }

(2)Dictionary.Values

         当只想遍历Value时

        foreach (int value in dic.Values)        {            Debug.Log("value " + value);        }

(3)Dictionary.Keys

         当只想遍历Key时

        foreach (string key in dic.Keys)        {            Debug.Log("key " + key);        }

        以上三种,后两种比第一种性能好,可根据需求来选择,我们通常并不是是key和value都想遍历,而只是其中一种


(4)不用foreach

        var enumerator = dic.GetEnumerator();        while (enumerator.MoveNext())        {            Debug.Log("while " + enumerator.Current.Key + " " + enumerator.Current.Value);                    }



2.规矩还是得遵守

        foreach (string key in dic.Keys)        {            dic[key] *= 2;        }
       以上这段代码看似没问题,编译也不报错,但实际运行不了。大家可以去试试,自然就会想到那条规矩没遵守了。

       实际项目中value通常是class,不是简单的数据类型,还有指针。如果想全部释放,那就得遍历。但上面那段代码不能运行。这种情况下如何做?给大家写一小段代码示范。

public class Test_Element{    public GameObject m_go = null;    public Test_Element(GameObject go)    {        m_go = go;    }    public void Release()    {        Debug.Log("Test_Element Release");        m_go = null;    }}

        Dictionary<string, Test_Element> dic = new Dictionary<string, Test_Element>();        dic.Add("a", new Test_Element(gameObject));        dic.Add("b", new Test_Element(gameObject));        dic.Add("c", new Test_Element(gameObject));        foreach (KeyValuePair<string, Test_Element> pair in dic)        {                       pair.Value.Release();        }        dic.Clear();        dic = null;

private Dictionary<string, Skill> dicActorSkillObjects = new Dictionary<string, Skill> ();
            for (int i = 0; i < dicActorSkillObjects.Keys.Count; i++)
            {
                Skill s = dicActorSkillObjects.ElementAt(i).Value;
                s.Destroy();
            }

0 0
原创粉丝点击