问题
Is there any performance difference between these two enumerations of a Hashset<string>
in C#?
foreach(string value1 in Hashset1) {
}
and
for(int i = 0; i < Hashset1.Count; i++) {
string _value1 = Hashset1.ElementAt(i);
}
Is there any other fast enumeration (performance wise) of a Hashset
?
回答1:
If it matters, you should benchmark and see for yourself what is the faster solution in your scenario.
In this case the second solution is pretty much guaranteed to be slower because ElementAt is an Enumerable extension method. It has an optimized path for IList<T>, which HashSet<T> does not implement. So it takes the "normal" path which is enumerating N elements from your IEnumerable<T>.
You can figure out for yourself that your second solution has O(N^2) complexity, while the first is surely O(N).
Is there any other fast enumeration of HashSet? No, I don't think so. That's what IEnumerable is for. But isn't this fast enough for you? Micro-benchmarking is useless and I would worry if your performance was bound by this.
回答2:
Yes, there is a huge difference between the two.
Enumerable.ElementAt(int)
is an O(n) operation, so your second is has O(n^2) complexity.
In contrast, enumerating the set through the enumerator is an O(n) operation.
来源:https://stackoverflow.com/questions/17180316/speed-of-enumerating-hashset