帮助C#.NET泛型集合性能和优化 [英] Help with C#.NET generic collections performance and optimization

查看:481
本文介绍了帮助C#.NET泛型集合性能和优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想优化一块.NET 2.0 C#code,它是这样的:

I am trying to optimize a piece of .NET 2.0 C# code that looks like this:

Dictionary<myType, string> myDictionary = new Dictionary<myType, string>();
// some other stuff
// inside a loop check if key is there and if not add element
if(!myDictionary.ContainsKey(currentKey))
{
   myDictionary.Add(currentKey, "");
}

看起来像字典已经使用谁写了这片code就算不需要(只有键被用来存储唯一值的列表),因为快于搜索的myType对象的列表。 这似乎显然是错误的字典中,只有按键,但我想知道什么是解决它的最好办法。

Looks like the Dictionary has been used by whoever wrote this piece of code even if not needed (only the key is being used to store a list of unique values) because faster than a List of myType objects for search. This seems obviously wrong as only the key of the dictionary but I am trying to understand what's the best way to fix it.

问题:

1),我似乎明白了我会得到哪怕只是使用.NET 3.5的HashSet一个良好的性能提升。这是正确的?

2)什么是优化高于在.NET 2.0和为什么code的最佳方法是什么?

修改: 这是现有的code我想优化,它是通过几十个上千项循环并为他们中的每一个调用的containsKey。有一定有这样做(即使是在.NET 2.0)的一个更好的办法! :)

EDIT: This is existing code I am trying to optimize, it's looping through dozens of thousands items and for each one of them is calling a ContainsKey. There's gotta be a better way of doing it (even in .NET 2.0)! :)

推荐答案

我想你需要打破这种分解成2个问题

I think you need to break this down into 2 questions

没有。根据您的故障,的HashSet&LT;&的myType GT; 显然是更好的选择,因为它的使用方式更准确地适合的场景

No. Based on your breakdown, HashSet<myType> is clearly the better choice because it's usage pattern more accurately fits the scenario

这是真的很主观的,只有一个分析器可以给你回答这个问题。可能你会看到集合中的每个元素一个很小的内存大小的改善。但在计算能力方面,我怀疑你会看到一个巨大的差别。只有分析器可以告诉你,如果有一个。

This is really subjective and only a profiler can give you the answer to this question. Likely you'll see a very minor memory size improvement per element in the collection. But in terms of raw computing power I doubt you'll see a huge difference. Only a profiler can tell you if there is one.

在你曾经做出的性能的相关改变你的code记得金科玉律。

Before you ever make a performance related change to your code remember the golden rule.

不要让任何性能相关的变化,直到探查告诉你precisely有什么不对您的code。

Don't make any performance related changes until a profiler has told you precisely what is wrong with your code.

违反此规则进行更改都只是猜测。一个分析器是在的方法来衡量业绩修复成功。

Making changes which violate this rule are just guesses. A profiler is the only way to measure success of a performance fix.

这篇关于帮助C#.NET泛型集合性能和优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆