foreach may be faster since you are not using an indexer
foreach (var value in dic.Values) Debug.Writeline(value)
Also, in terms of speed, Debug.Writeline is probably not the best option (what are you going to do with 2 million debugging entries anyway?). Consider writing to a file, database, etc.
EDIT Looking at the reflector, searching for a value in SortedDictionry comes down to a binary search:
internal virtual Node<T> FindNode(T item) { int num; for (Node<T> node = this.root; node != null; node = (num < 0) ? node.Left : node.Right) { num = this.comparer.Compare(item, node.Item); if (num == 0) { return node; } } return null; }
Implementing an Iteration of SortedDictionary seems a bit more complicated:
public bool MoveNext() { this.tree.VersionCheck(); if (this.version != this.tree.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } if (this.stack.Count == 0) { this.current = null; return false; } this.current = this.stack.Pop(); SortedSet<T>.Node item = this.reverse ? this.current.Left : this.current.Right; SortedSet<T>.Node node2 = null; SortedSet<T>.Node node3 = null; while (item != null) { node2 = this.reverse ? item.Right : item.Left; node3 = this.reverse ? item.Left : item.Right; if (this.tree.IsWithinRange(item.Item)) { this.stack.Push(item); item = node2; } else { if ((node3 == null) || !this.tree.IsWithinRange(node3.Item)) { item = node2; continue; } item = node3; } } return true; }
It seems to support a stack whose top element is the smallest (or largest, depending on direction), and thus always the one that needs to be popped up and returned during the iteration. I did not do any complexity analysis, but it should be significantly more efficient than running a binary search every time.
source share