Saturday, June 15, 2013

Performance difference between for and foreach loop



Guys , I am going to explain very interesting fact in this article. I think all of you are familiar with both for and foreach loop. Now if I ask you which one is faster ? Hmm..Don’t know .  write ?
Guys for loop is much faster than foreach loop. Because according to below code .The operation foreach(int a in) takes much more time than operation  for (int i = 0; i < Count.Count; i++) in for loop, And that’s why it takes more time.



List<Int32> Count = new List<int>();
            List<Int32> lst1 = new List<Int32>();
            List<Int32> lst2 = new List<Int32>();

            for (int i = 0; i < 10000; i++)
            {
                Count.Add(i);
            }

            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < Count.Count; i++)
            {
                lst1.Add(i);
            }
            sw.Stop();
            Console.Write("For Loop :- "+ sw.ElapsedTicks+"\n");
            sw.Restart();

            foreach (int a in Count)
            {
                lst2.Add(a);
            }
            sw.Stop();
            Console.Write("Foreach Loop:- " +  sw.ElapsedTicks);
            Console.ReadLine();


No comments:

Post a Comment