c# - Improving access time on SortedDictionary -
i have 2 millions items in sorteddictionary<string, myclass>
i've done following , takes ages, ideas?
for(int = 0; i<dic.count-1; i++) { debug.writeline(dic.elementat(i).value.tostring()); }
the sorteddictionary<tkey, tvalue>
class not directly support (fast) retrieval index; internally implemented binary search tree. consequently, every call linq enumerable.elementat
method you've got there creates new enumerator iterates each value of sequence represented key-value pairs in collection (sorted key) from beginning until reaches desired index. means loop going have pull 1 + 2 + 3 + ... + count
(roughly 2 trillion) elements before completes, making (atleast) quadratic in time-complexity.
try instead, should run in linear time:
foreach(var myclass in dic.values) debug.writeline(myclass);
if want fast access index (from provided code, there doesn't seem reason indicate this), consider using sortedlist<tkey, tvalue>
instead. there downsides choice (slower non-appending inserts , deletes) should evaluate.
i notice loop condition i < dic.count - 1
rather more common i < dic.count
. either off-by-one bug, or perhaps intend not consider last value in dictionary. in latter case, maintain local variable serving counter, or linq:
foreach(var myclass in dic.values.take(dic.count - 1)) debug.writeline(myclass);
Comments
Post a Comment