我已经使用了VS profilier,并注意到大约40%的时间程序花费在下面的行中.我正在使用title1,color1因为Visual Studio或Resharper建议这样做.下面的代码中是否存在任何性能问题?
Dictionary<Item, int> price_cache = new Dictionary<Item, int>();
....
string title1 = title;
string color1 = color;
if (price_cache.Keys.Any(item => item.Title == title && item.Color == color))
{
price = price_cache[price_cache.Keys.First(item => item.Title == title11 && item.Color == color1)];
Run Code Online (Sandbox Code Playgroud)
问题是您的Keys.Any方法遍历字典中的所有键以查找是否存在匹配项.之后,您使用该First方法再次执行相同的操作.
字典适用于已经拥有密钥并希望快速获取值的操作.在这种情况下,它将计算密钥的哈希码(Item在您的情况下),并使用它来"跳转"到存储项目的存储桶.
首先,您需要使自定义比较器让您Dictionary知道如何比较项目.
class TitleColorEqualityComparer : IEqualityComparer<Item>
{
public bool Equals(Item a, Item b)
{
// you might also check for nulls here
return a.Title == b.Title &&
a.Color == b.Color;
}
public int GetHashCode(Item obj)
{
// this should be as much unique as possible,
// but not too complicated to calculate
int hash = 17;
hash = hash * 31 + obj.Title.GetHashCode();
hash = hash * 31 + obj.Color.GetHashCode();
return hash;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,使用自定义比较器实例化您的字典:
Dictionary<Item, int> price_cache =
new Dictionary<Item, int>(new TitleColorEqualityComparer());
Run Code Online (Sandbox Code Playgroud)
从这一点开始,你可以简单地写:
Item some_item = GetSomeItem();
price_cache[some_item] = 5; // to quickly set or change a value
Run Code Online (Sandbox Code Playgroud)
或者,搜索字典:
Item item = GetSomeItem();
int price = 0;
if (price_cache.TryGetValue(item, out price))
{
// we got the price
}
else
{
// there is no such key in the dictionary
}
Run Code Online (Sandbox Code Playgroud)
[编辑]
并再次强调:永远不要迭代Keys财产来寻找钥匙.如果你这样做,你根本不需要Dictionary,你可以简单地使用一个列表并获得相同的(甚至更好的性能).