Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Foreach vs AddRange
Message
 
 
To
11/08/2009 13:47:23
General information
Forum:
ASP.NET
Category:
Other
Environment versions
Environment:
C# 3.0
Miscellaneous
Thread ID:
01417359
Message ID:
01417363
Views:
51
Did you try to initialize the buf array with some values for your tests?

And also run the tests separately, not in one class?

>from http://msdn.microsoft.com/en-us/library/ms973839.aspx
>
>
>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:  ......
>
>
>
>That's what I thought too - One call is faster than many calls
>
>Much to my surprise - the many calls is faster than the one call in the following scenario (code below)
>
>When increasing the size of the array to 256 ( and nTimes = 1000000) the AddRange is (a bit) faster
>
>My conclusion - use Foreach if adding smaller collections - or better use an extension method that tests the # of items to add and then decides whether to use foreach or addrange
>
>Anyone has a clue why the foreach is faster for adding a small # of items ?
>
>
>
>	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();
>			}
>		}
>		//______________________________________________________________________
>	
>
>	}
>
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform