I noticed that the fastest way (at the moment) is to repeat using the dictionary with the modification:
//Just a dumb class class Test<T> { public T value; public Test() { } public Test(T v) { value = v; } } Dictionary<int, Test<object>> dic = new Dictionary<int, Test<object>>(); //Init dictionary foreach (KeyValuePair<int, Test> pair in dic) { pair.Value.value = TheObject;//Modify }
VS
List<int> keys = new List<int>(dic.Keys); //This is fast operation foreach (int key in keys) { dic[key] = TheObject; }
The first takes about 2.2 seconds, and the second takes 4.5 s (the dictionary size is 1000 and repeated 10k times, changing the dictionary size to 10 did not change the coefficients). There was also no big deal with getting a list of keys, the value of the [key] get dictionary is just a slow VS built on iteration. In addition, if you want an even higher speed to use the hard coded type for the silent ("Test") class, with this I got it about 1.85 s (from hardcoded to "object").
EDIT:
Anna has sent the same solution before: https://stackoverflow.com/a/316618/
Risord Aug 17 '13 at 12:18 2013-08-17 12:18
source share