More details:
The release build was used in the test
Software used in the test:
- Windows XP Pro SP2
- .NET Framework 2.0
The specs of my computer (where the test was done) are:
- CPU Intel 1.6GHz Dual Core
- 1024 MB RAM
Used Code
using System; using System.Collections.Generic; using System.Text; namespace for_vs_foreach { class Program { static void Main(string[] args) { const int LOOP_COUNT = 10000000; int myVar; MyCustomObject[] customObjects = new MyCustomObject[LOOP_COUNT]; for (int i = 0; i < LOOP_COUNT; i++) { customObjects[i] = new MyCustomObject(i); } System.Threading.Thread.Sleep(1000); // foreach // DateTime beforeForeach = DateTime.Now; foreach (MyCustomObject customObject in customObjects) { myVar = customObject.Var; } DateTime afterForeach = DateTime.Now; // for // DateTime beforeFor = DateTime.Now; for (int i = 0; i < LOOP_COUNT; i++) { myVar = customObjects[i].Var; } DateTime afterFor = DateTime.Now; Console.WriteLine("{0} (foreach test results)", afterForeach.Subtract(beforeForeach)); Console.WriteLine("{0} (for test results)", afterFor.Subtract(beforeFor)); Console.Read(); } } public class MyCustomObject { public MyCustomObject(int var) { _var = var; } private int _var; public int Var { get { return _var; } set { _var = value; } } } }Results: 00:00:00.0625000 (foreach test results)
00:00:00.0625000 (for test results)
No comments:
Post a Comment