【发布时间】:2020-02-29 22:12:50
【问题描述】:
我想存储一个点集合,它们是Point 类的对象。 (Point 包含positionX、positionY、electricalPotential 等属性)
他们每个人都应该有一个索引i,但不需要以任何方式订购。
这就是为什么我首先使用字典Dictionary<int, Point> meshpoints。
第一个问题:
如果我只想存储具有特定索引/键的对象,尤其是涉及到每个元素的添加、搜索和循环等性能问题时,字典是存储数据的最有效方式吗?
第二个问题:
如果我想添加一个新点,我如何获得“下一个”免费密钥?就像我有带有哈希键 0、1、2、3 和 4 的字典,我如何获得下一个项目键的 5?
选项 1: meshpoints.Keys.Max() 和 meshpoints.Keys.Last() 在我的测试中花费了很多时间。
Dictionary<int, string> meshpoints = new Dictionary<int, string>();
meshpoints.Add(meshpoints.Keys.Max() + 1, "itemA");
meshpoints.Add(meshpoints.Keys.Max() + 1, "itemB");
选项 2: 在我的性能测试中,创建一个单独的变量 counter 非常快,但它真的是最优雅的方式吗?我的意思是,你总是有一个带有字典的单独整数值到所有方法等。...
Dictionary<int, string> meshpoints = new Dictionary<int, string>();
int counter = 0;
meshpoints.Add(counter, "itemA");
counter++;
meshpoints.Add(counter, "itemB");
counter++;
选项 3: meshpoints.Count() 不起作用,当我也随时删除项目时。
【问题讨论】:
-
1) 是的。 2)创建一个单独的变量
counter。或者,如果您不会从字典中删除项目,则使用meshpoints.Count来表示下一个项目。但是,如果您永远不会删除它们,只需使用List而不是 Dictionary 并将索引设为标识符。如果永远不会删除meshpoints[0],则meshpoints[3]始终是同一个对象。如果您可以删除它们,请使用字典和计数器变量。 -
@EdPlunkett:除了“删除”操作之外,我们是否还应该考虑随机访问?如果您关心性能和随机访问,我认为您仍然应该选择在字典中存储点的类。
-
@vonludi
List<T>'s index operator is a wrapper around an array indexing operation。这并不慢。你在考虑一个链表吗? -
index没有身份语义。如果删除了位于该项目之前的另一个项目,则该项目的索引可能会更改。也许你的意思是id而不是index? -
你能有多个坐标相同的点吗?
标签: c# list performance dictionary hashtable