Click here to Skip to main content
15,886,830 members
Articles / General Programming / Threads

Comparison between Different Methods to Iterate Over a List of Items

Rate me:
Please Sign up or sign in to vote.
4.84/5 (9 votes)
7 Mar 2011CPOL10 min read 33.5K   163   17  
Comparison between different methods to iterate over a list of items and see which method is the most effective
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace LoopExecution
{

    public class LoopExecution<T>
    {

        public delegate void MethodToExecute(object sender, LoopExecutionEventArgs e);
        public event MethodToExecute ExecutionMethod;

        protected void OnExecuteMethod(object sender, LoopExecutionEventArgs e)
        {
            if (ExecutionMethod != null)
            {
                ExecutionMethod(sender, e);
            }
        }

        public List<T> CollectionToIterateOver { get; set; }

        public long NormalLoopTime { get; set; }
        public long ThreadLoopTime { get; set; }
        public long ThreadPoolLoopTime { get; set; }
        public long TaskLoopTime { get; set; }
        Stopwatch watch = new Stopwatch();

        public void Execute()
        {
            NormalExecute();
            ThreadExecute();
            ThreadPoolExecute();
            TaskParallelExecute();
        }

        private void NormalExecute()
        {
            watch.Start();
            NormalWhileLoop();
            NormalLoopTime = watch.ElapsedMilliseconds;
            watch.Reset();
        }

        private void NormalWhileLoop()
        {
            for (int i = 0; i < this.CollectionToIterateOver.Count; i++)
            {
                LoopExecutionEventArgs e = new LoopExecutionEventArgs();
                StackFrame stackFrame = new StackFrame();
                e.MethodName = stackFrame.GetMethod().ToString();
                e.LoopExecutionNumber = i;
                e.ObjectToOperateOn = CollectionToIterateOver[i];

                OnExecuteMethod(this, e);
            }
        }

        private void ThreadExecute()
        {
            watch.Start();
            ThreadLoop();
            ThreadLoopTime = watch.ElapsedMilliseconds;
            watch.Reset();
        }

        private void ThreadLoop()
        {

            for (int i = 0; i < this.CollectionToIterateOver.Count; i++)
            {
                Thread t = new Thread(x =>
                {
                    LoopExecutionEventArgs e = new LoopExecutionEventArgs();
                    StackFrame stackFrame = new StackFrame();
                    e.MethodName = stackFrame.GetMethod().ToString();
                    e.LoopExecutionNumber = (int)x;
                    e.ObjectToOperateOn = CollectionToIterateOver[(int)x];
                    OnExecuteMethod(this, e);
                });
                t.Start(i);
            }
        }

        private void ThreadPoolExecute()
        {
            watch.Start();
            ThreadPoolLoop();
            ThreadPoolLoopTime = watch.ElapsedMilliseconds;
            watch.Reset();
        }
        
        private void ThreadPoolLoop()
        {
            int toProcess = this.CollectionToIterateOver.Count;
            using (ManualResetEvent resetEvent = new ManualResetEvent(false))
            {
                for (int i = 0; i < this.CollectionToIterateOver.Count; i++)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(x =>
                        {
                            LoopExecutionEventArgs e = new LoopExecutionEventArgs();
                            StackFrame stackFrame = new StackFrame();
                            e.MethodName = stackFrame.GetMethod().ToString();
                            e.LoopExecutionNumber = (int)x;
                            e.ObjectToOperateOn = CollectionToIterateOver[(int)x];
                            OnExecuteMethod(this, e);
                            if (Interlocked.Decrement(ref toProcess) == 0)
                                resetEvent.Set();

                        }
                                 ), i);
                }
                resetEvent.WaitOne();
            }
        }

        private void TaskParallelExecute()
        {
            watch.Start();
            TaskParallelLibraryLoop();
            TaskLoopTime = watch.ElapsedMilliseconds;
            watch.Reset();
        }

        private void TaskParallelLibraryLoop()
        {
            Parallel.For(0, this.CollectionToIterateOver.Count, i =>
                {
                    LoopExecutionEventArgs e = new LoopExecutionEventArgs();
                    StackFrame stackFrame = new StackFrame();
                    e.MethodName = stackFrame.GetMethod().ToString();
                    e.LoopExecutionNumber = i;
                    e.ObjectToOperateOn = CollectionToIterateOver[i];
                    OnExecuteMethod(this, e);
                })
            ;
        }

        public class LoopExecutionEventArgs : EventArgs
        {
            public String MethodName { get; set; }
            public T ObjectToOperateOn { get; set; }
            public int LoopExecutionNumber { get; set; }
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) FTSE russell
United Kingdom United Kingdom
Software Engineer who started coding when I was 5. Core focus is to meet clients real business needs through initial consultation, followed by a communicative and collaborative approach. Delivers applications using C# .net and MS SQL Server. Comfortable working independently, in a team, or mentoring to meets deadlines irrelevant of pressure.

Currently interested in cloud computing with a focus on Microsoft Azure

Comments and Discussions