>Use AddRange to add a whole collection, rather than adding each item in the collection iteratively. >Nearly all windows controls and collections have both Add and AddRange methods, and each is optimized for a different purpose. >Add is useful for adding a single item, whereas AddRange has some extra overhead but wins out when adding multiple items. >Here are just a few of the classes that support Add and AddRange: ...... > >>
> class test3 > { > const int Size = 16; > const int nTimes = 6000000; > //______________________________________________________________________ > static void Main() > { > ExecuteTimed.Run(UseAddRange, false); // 9.77 sec > > ExecuteTimed.Run(UseForeach, true); // 2.85 sec > > } > //______________________________________________________________________ > static void UseAddRange() > { > int[] buf = new int[Size]; > > List<int> list = new List<int>(); > > for (int i = nTimes; --i != 0; ) > { > list.AddRange(buf); > list.Clear(); > } > } > //______________________________________________________________________ > static void UseForeach() > { > int[] buf = new int[Size]; > > List<int> list = new List<int>(); > > for (int i = nTimes; --i != 0; ) > { > foreach (int item in buf) > list.Add(item); > > list.Clear(); > } > } > //______________________________________________________________________ > > > } >