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
- Unity中的Dictionary(字典)的遍历
- Python中的字典(Dictionary)
- C# 字典 Dictionary 遍历
- C# 字典 Dictionary 遍历
- 字典(dictionary)的设计
- .net中的Dictionary字典类的使用方法
- C#中的Dictionary字典的用法介绍
- swift中的字典Dictionary
- Java中的字典Dictionary
- OC中的字典dictionary
- Swift 中的字典 (Dictionary)
- swift_005(Swift的Dictionary 字典)
- Python 字典(dictionary)的排序
- C#的Dictionary字典
- Python字典(Dictionary)
- swift-字典(Dictionary)
- Swift-字典(Dictionary)
- python dictionary(字典)
- 设计模式C++实现(13)——中介者模式
- Hive SQL 一些窗口函数,分析函数的使用小例子
- Java开源PDF类库 分类列表
- 转发vitamio使用的一些错误更改
- Opencv配置和Imagewatch使用
- Unity中的Dictionary(字典)的遍历
- configure --prefix=/ & yum install 路径
- 深拷贝浅拷贝
- linux消息队列
- 查询多个表的字段到一个新实体中(left join 右表有内容为空时,可以保留左、右表不为空的内容)
- Android vector 标签 pathData 详解
- centos7在vmware上安装后不能连接网络和没有ifconfig命令
- liunx终端进入、退出python命令行
- spring boot入门实现