2

I have written the following code to print the item values inside the list. Now I want to measure which one is faster as going forward I will have huge list to deal with. And please specify why you think that's better (if any evidences)

So how do I calculate the processing time? Is manually creating a bulky List is the only option?

  public void printMedod(string strPrintListVal)
        {
            Console.WriteLine(strPrintListVal);
        }


        static void Main(string[] args)
        {
            Program p1 = new Program();

            List<string> listString = new List<string> { "Rox","Stephens","Manahat","Lexus",":)"};
            listString.ForEach(p1.printMedod);
            Console.ReadKey();
        }

I can also do the same thing using GetEnumerator:

        static void Main(string[] args)
        {
            List<string> listString = new List<string> { "Rox","Stephens","Manahat","Lexus",":)"};
            var enumerator = listString.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var pair = enumerator.Current;
                Console.WriteLine(pair);
            }
            Console.ReadKey();
        }
Simsons
  • 12,295
  • 42
  • 153
  • 269

3 Answers3

5

I'd ForEach my way through the list, but I've been told a for loop is faster than anything else:

for(int i = 0;i < stringList.Length; i++)
{
    Console.WriteLine(stringList[i]);
}
Alex
  • 23,004
  • 4
  • 39
  • 73
3

You can use LinqPad, it displays an execution time

saj
  • 4,626
  • 2
  • 26
  • 25
1

Neither is the best option here, just do

static void Main(string[] args)
{
    var stringList = new List<string> 
        { "Rox", "Stephens", "Manahat", "Lexus", ":)" };

    foreach(var s in stringList)
    {
        Console.WriteLine(s);
    }

    Console.ReadKey();
}

EDIT

use a StopWatch more info in this question

using System.Diagnotics;

var stopWatch = new StopWatch();

stopWatch.Start();

// Do somthing
// If somthing is really fast do lots of somthing

stopWatch.Stop();

// The duration is a TimeSpan in stopWatch.Elapsed;
Community
  • 1
  • 1
Jodrell
  • 34,946
  • 5
  • 87
  • 124
  • 1
    Thanks, but how do I get to know? Is there way we can measure the processing time – Simsons Jul 10 '12 at 09:03
  • As someone said in the comments above, that is inlined to a `while`-loop with `GetEnumerator()` so it's not faster then writing code using `GetEnumerator()` yourself. – Karl-Johan Sjögren Jul 10 '12 at 09:05
  • @Karl-JohanSjögren, agreed, but its not slower either but more common and therefore, I suggest, more readable. – Jodrell Jul 10 '12 at 09:13