Click here to Skip to main content
15,891,204 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.7K   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.Threading;
using System.IO;

namespace LoopExecution.Application
{
    class Program
    {
        struct Results
        {
            public long NormalLoopTime { get; set; }
            public long ThreadLoopTime { get; set; }
            public long ThreadPoolLoopTime { get; set; }
            public long TaskLoopTime { get; set; }
        }

        static public int TypeOfDelegateToRun { get; set; }

        static void Main(string[] args)
        {
            Arguments arguments = new Arguments(args);

            SortedList<int, Results> listOfResults = new SortedList<int, Results>();
            int startOfRun = 0;
            int endOfRun = 0;

            startOfRun = InitiateStartOfRunNumber(arguments);
            endOfRun = InitiateEndOfRunNumber(arguments);
            InitiateTypeOfDelegateToRun(arguments);

            List<int> listOfInt = new List<int>();
            for (int i = 0; i < startOfRun; i++)
            {
                listOfInt.Add(i);
            }

            for (int i = startOfRun; i < endOfRun; i++)
            {
                listOfInt.Add(i);
                Results results = ExecuteThreadRun(listOfInt);
                listOfResults.Add(i, results);
            }

            if (arguments["printToScreen"] != null)
            {
                PrintResultsToScreen(listOfResults);
            }
            else
            {
                SaveResultsToFile(listOfResults);
            }
            Console.ReadLine();
        }
       
        private static int InitiateStartOfRunNumber(Arguments arguments)
        {
            int startOfRun = 0;
            if (arguments["startNumber"] != null)
            {
                if (!int.TryParse(arguments["startNumber"], out startOfRun))
                {
                    throw new Exception("Invalid start number");
                }
            }
            else
            {
                Console.Write("Please enter start number : ");
                string startNumber = Console.ReadLine();

                while (!int.TryParse(startNumber, out startOfRun))
                {
                    Console.Write("Incorrect number. Please enter start number again : ");
                    startNumber = Console.ReadLine();
                }
            }
            return startOfRun;
        }

        private static int InitiateEndOfRunNumber(Arguments arguments)
        {
            int endOfRun = 0;
            if (arguments["endNumber"] != null)
            {
                if (!int.TryParse(arguments["endNumber"], out endOfRun))
                {
                    throw new Exception("Invalid end number");
                }
            }
            else
            {
                Console.Write("Please enter end number : ");
                string endNumber = Console.ReadLine();

                while (!int.TryParse(endNumber, out endOfRun))
                {
                    Console.Write("Incorrect number. Please enter end number again : ");
                    endNumber = Console.ReadLine();
                }
            }
            return endOfRun;
        }

        private static void InitiateTypeOfDelegateToRun(Arguments arguments)
        {
            if (arguments["endNumber"] != null)
            {
                switch (arguments["endNumber"].ToUpper())
                {
                    case "WRITELINE":
                        TypeOfDelegateToRun = 1;
                        break;
                    case "SLEEP":
                        TypeOfDelegateToRun = 2;
                        break;
                    default:
                        throw new Exception("Invalid delegate choice number");
                }
            }
            else
            {
                Console.WriteLine("Please choose which type of delgate to use : ");
                Console.WriteLine("\t1) Only do Console.WriteLine to screen. ");
                Console.WriteLine("\t2) Perform a sleep every 11 or 23 iteration. ");
                string delegateChoice = Console.ReadLine();
                int delgateChoiceint = 0;
                while ((!int.TryParse(delegateChoice, out delgateChoiceint)) || !(0 < delgateChoiceint && delgateChoiceint < 3))
                {
                    Console.Write("Incorrect number. Please enter choice again : ");
                    delegateChoice = Console.ReadLine();
                }

                TypeOfDelegateToRun = delgateChoiceint;
            }
        }

        private static Results ExecuteThreadRun(List<int> listOfInt)
        {
            LoopExecution<int> loopExecution = new LoopExecution<int>();

            switch (TypeOfDelegateToRun)
            {
                case 1:
                    loopExecution.ExecutionMethod += new LoopExecution<int>.MethodToExecute(loopExecution_ExecutionMethodConsoleWriteLine);
                    break;
                case 2:
                    loopExecution.ExecutionMethod += new LoopExecution<int>.MethodToExecute(loopExecution_ExecutionMethodSleep);
                    break;
                default:
                    break;
            }          

            loopExecution.CollectionToIterateOver = listOfInt;

            loopExecution.Execute();

            Results results = new Results();

            results.NormalLoopTime = loopExecution.NormalLoopTime;
            results.ThreadLoopTime = loopExecution.ThreadLoopTime;
            results.ThreadPoolLoopTime = loopExecution.ThreadPoolLoopTime;
            results.TaskLoopTime = loopExecution.TaskLoopTime;
            return results;
        }

        private static void PrintResultsToScreen(SortedList<int, Results> listOfResults)
        {
            Console.WriteLine("{0},{1},{2},{3},{4}", "TestRun", "Normal", "Tread", "ThreadPool", "Task");

            foreach (int key in listOfResults.Keys)
            {
                Console.WriteLine("{0},{1},{2},{3},{4}", key, listOfResults[key].NormalLoopTime,
                        listOfResults[key].ThreadLoopTime, listOfResults[key].ThreadPoolLoopTime,
                        listOfResults[key].TaskLoopTime);
            }
        }

        private static void SaveResultsToFile(SortedList<int, Results> listOfResults)
        {
            FileStream fs = File.Create(string.Format(".\\ThreadResults{0}.csv", DateTime.Now.ToString("yyyyMMddhhmmss")));
            StreamWriter sw = new StreamWriter(fs);

            sw.WriteLine("{0},{1},{2},{3},{4}", "TestRun", "Normal", "Thread", "ThreadPool", "Task");

            foreach (int key in listOfResults.Keys)
            {
                sw.WriteLine("{0},{1},{2},{3},{4}", key, listOfResults[key].NormalLoopTime,
                        listOfResults[key].ThreadLoopTime, listOfResults[key].ThreadPoolLoopTime,
                        listOfResults[key].TaskLoopTime);
            }

            sw.Flush();
            sw.Close();
        }

        static void loopExecution_ExecutionMethodConsoleWriteLine(object sender, LoopExecution<int>.LoopExecutionEventArgs e)
        {
            Console.WriteLine("{0} number {1}. Thread name : {2}", e.MethodName, e.LoopExecutionNumber, Thread.CurrentThread.ManagedThreadId);
        }

        static void loopExecution_ExecutionMethodSleep(object sender, LoopExecution<int>.LoopExecutionEventArgs e)
        {

            if (e.LoopExecutionNumber % 11 == 0)
            {
                Thread.Sleep((int)(e.LoopExecutionNumber * 0.149) + 1);
            }
            else if (e.LoopExecutionNumber % 23 == 0)
            {
                Thread.Sleep((int)(e.LoopExecutionNumber * 0.344));
            }
            Console.WriteLine("{0} number {1}. Thread name : {2}", e.MethodName, e.LoopExecutionNumber, Thread.CurrentThread.ManagedThreadId);
        }
    }
}

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