DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why We Still Struggle With Manual Test Execution in 2025
  • Advancing Shift-Left Testing With Generative AI
  • Is It Okay To Stop Running Your Tests After the First Failure?
  • Error Handling Inside Kumologica Subflow

Trending

  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • AI-Based Threat Detection in Cloud Security
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  1. DZone
  2. Data Engineering
  3. Data
  4. For vs. For Each vs. While in C#

For vs. For Each vs. While in C#

We check out how fast each of these loops can loop through an array and a list. Which one do you think will prevail?

By 
Faisal Pathan user avatar
Faisal Pathan
·
Updated May. 09, 19 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
19.1K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction 

I am often asked by some people/colleagues, "which loop is faster?" "Which loop has higher performance?" Etc. I have heard that the For loop is faster than the For...each loop but I have never tried it before. So, I decided to see how big the difference is among all the loops and which one is faster at looping through an array and a list in terms of speed and performance.

Let's start our journey to fin the best C# loop. For this exercise, I'll be creating a console application in Visual Studio 2017.  

First, I'm going to create one class called CustomStopwatch which helps to track the starting and ending times of loops. 

using System;  
using System.Diagnostics;  

namespace ConsoleApp2  
{  
    public class CustomStopwatch : Stopwatch  
    {  

        public DateTime? StartAt { get; private set; }  
        public DateTime? EndAt { get; private set; }  


        public void Start()  
        {  
            StartAt = DateTime.Now;  

            base.Start();  
        }  

        public void Stop()  
        {  
            EndAt = DateTime.Now;  

            base.Stop();  
        }  

        public void Reset()  
        {  
            StartAt = null;  
            EndAt = null;  

            base.Reset();  
        }  

        public void Restart()  
        {  
            StartAt = DateTime.Now;  
            EndAt = null;  

            base.Restart();  
        }  

    }  
}  


Performance Of The Loops In C#

Custom stop watch code in C#

Now, it is time to write code in the Program.cs class. First, I'm going to implement a For loop on:

  • a single integer.
  • an array.
  • a list.
using System;  
using System.Linq;  

namespace ConsoleApp2  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            CustomStopwatch sw = new CustomStopwatch();  
            sw.Start();  
            for (int i = 0; i < 10000; i++) Console.WriteLine(i);  
            sw.Stop();  

            CustomStopwatch sw1 = new CustomStopwatch();  
            int[] array = Enumerable.Range(0, 10000).ToArray();  
            sw1.Start();  
            for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i]);  
            sw1.Stop();  

            CustomStopwatch sw2 = new CustomStopwatch();  
            var arrList = array.ToList();  
            sw2.Start();  
            for (int i = 0; i < arrList.Count; i++) Console.WriteLine(arrList[i]);  
            sw2.Stop();  

            Console.WriteLine($"for Time elapsed: {sw.ElapsedMilliseconds} Milliseconds, StartAt: {sw.StartAt.Value}, EndAt: {sw.EndAt.Value}");  
            Console.WriteLine($"for on array Time elapsed: {sw1.ElapsedMilliseconds} Milliseconds, StartAt: {sw1.StartAt.Value}, EndAt: {sw1.EndAt.Value}");  
            Console.WriteLine($"for on list Time elapsed: {sw2.ElapsedMilliseconds} Milliseconds, StartAt: {sw2.StartAt.Value}, EndAt: {sw2.EndAt.Value}");  
            Console.ReadKey();  
        }  

    }  
}  


Performance Of The Loops In C#

For Loop Test


Let's run the script to see output and execution time in milliseconds.

Performance Of The Loops In C#

For Loop Performance

As per my output, the For loop on the list is faster.  

Let's compare the For...each loop on the list and array.

using System;  
using System.Linq;  

namespace ConsoleApp2  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            int[] array = Enumerable.Range(0, 10000).ToArray();  
            var arrList = array.ToList();  

            CustomStopwatch sw1 = new CustomStopwatch();  
            sw1.Start();  
            foreach (var arr in array) Console.WriteLine(arr);  
            sw1.Stop();  

            CustomStopwatch sw2 = new CustomStopwatch();  
            sw2.Start();  
            foreach (var arr in arrList) Console.WriteLine(arr);  
            sw2.Stop();  

            Console.Clear();  
            Console.WriteLine($"for each on array Time elapsed: {sw1.ElapsedMilliseconds} Milliseconds, StartAt: {sw1.StartAt.Value}, EndAt: {sw1.EndAt.Value}");  
            Console.WriteLine($"for each on list Time elapsed: {sw2.ElapsedMilliseconds} Milliseconds, StartAt: {sw2.StartAt.Value}, EndAt: {sw2.EndAt.Value}");  
            Console.ReadKey();  
        }  
    }  
}  


Performance Of The Loops In C#

For...Each Loop


Let's run to see output and execution time in milliseconds.  

Performance Of The Loops In C#

For...Each Loop Performance


Here, the For...each loop on the list is faster. 

Let's compare the While loop on the list and an array.

using System;  
using System.Linq;  

namespace ConsoleApp2  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            int[] array = Enumerable.Range(0, 10000).ToArray();  
            var arrList = array.ToList();  

            CustomStopwatch sw1 = new CustomStopwatch();  
            sw1.Start();  
            int i = 0;  
            while (i != array.Length) Console.WriteLine(array[i++]);  
            sw1.Stop();  

            CustomStopwatch sw2 = new CustomStopwatch();  
            sw2.Start();  
            i = 0;  
            while (i != arrList.Count) Console.WriteLine(arrList[i++]);  
            sw2.Stop();  

            Console.Clear();  
            Console.WriteLine($"while on array Time elapsed: {sw1.ElapsedMilliseconds} Milliseconds, StartAt: {sw1.StartAt.Value}, EndAt: {sw1.EndAt.Value}");  
            Console.WriteLine($"while on list Time elapsed: {sw2.ElapsedMilliseconds} Milliseconds, StartAt: {sw2.StartAt.Value}, EndAt: {sw2.EndAt.Value}");  
            Console.ReadKey();  
        }  
    }  
}  


Performance Of The Loops In C#

While Loop


And the output of While loop is as below.  

Performance Of The Loops In C#

While Loop Performance


The While loop is faster at looping through the list.  

Conclusion  

This article covered a quick comparison of For, For...each, and While loops on arrays and lists. As I said before, an array is faster than a list, but, as per my observation (in terms of iteration), a list is faster, as we can see in the outputs. I think it depends on the data and the way you use the data. My personal suggestion is that we should use a list instead of an array for the below reasons.

  • In an array, we need to know the array's size, and we can't change the array's size (we have the Resize() method but it will change the reference) where a list can grow after it's created.
  • In a list, we don't need to worry about the list's size or  an 'index out of bounds' exception.
  • A list provides lots of helpful methods like Add, Find, etc.
  • Lists are easy to read. 

Please give your valuable feedback/comments/questions about this article below. Please let me know how you like and understand this article and how I could improve it.

Data structure Execution (computing) Testing C# (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Why We Still Struggle With Manual Test Execution in 2025
  • Advancing Shift-Left Testing With Generative AI
  • Is It Okay To Stop Running Your Tests After the First Failure?
  • Error Handling Inside Kumologica Subflow

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!