I’ve used VS profilier and noticed that ~40% of the time program spends in the lines below.
I’m using title1 and color1 because either Visual Studio or Resharper suggested to do so. Are there any perfomance issues in the code below?
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)];
The problem is that your
Keys.Anymethod iterates through all keys in your dictionary to find if there is a match. After that, you use theFirstmethod to do the same thing again.Dictionary is suited for operations when you already have the key and want to get the value fast. In that case, it will calculate the hash code of your key (
Item, in your case) and use it to “jump” to the bucket where your item is stored.First, you need to make your custom comparer to let the
Dictionaryknow how to compare items.Then, instantiate your dictionary using your custom comparer:
From this point on, you can simply write:
or, to search the dictionary:
[Edit]
And to emphasize again: never iterate the
Keysproperty to look for a key. If you do that, you don’t need aDictionaryat all, you can simply use a list and get same (even slightly better performance).