Want more features on Pastebin? Sign Up, it's FREE!
Guest

C#, For Loops, and speed test… Exact same loop faster second time around

By: a guest on Feb 28th, 2012  |  syntax: None  |  size: 1.27 KB  |  views: 32  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. public Int64 ReturnDifferenceA()
  2. {
  3.   User[] arrayList;
  4.   Int64 firstTicks;
  5.   IList<User> userList;
  6.   Int64 secondTicks;
  7.   System.Diagnostics.Stopwatch watch;
  8.  
  9.   userList = Enumerable
  10.               .Range(0, 1000)
  11.               .Select(currentItem => new User()).ToList();
  12.  
  13.   arrayList = userList.ToArray();
  14.  
  15.   watch = new Stopwatch();
  16.   watch.Start();
  17.  
  18.   for (Int32 loopCounter = 0; loopCounter < arrayList.Count(); loopCounter++)
  19.   {
  20.      DoThings(arrayList[loopCounter]);
  21.   }
  22.  
  23.   watch.Stop();
  24.   firstTicks = watch.ElapsedTicks;
  25.  
  26.   watch.Reset();
  27.   watch.Start();
  28.   for (Int32 loopCounter = 0; loopCounter < arrayList.Count(); loopCounter++)
  29.   {
  30.      DoThings(arrayList[loopCounter]);
  31.   }
  32.   watch.Stop();
  33.   secondTicks = watch.ElapsedTicks;
  34.  
  35.   return firstTicks - secondTicks;
  36. }
  37.        
  38. differenceList = Enumerable
  39.                  .Range(0, 50)
  40.                  .Select(currentItem => ReturnDifferenceA()).ToList();
  41. average = differenceList.Average();
  42.  
  43. differenceListA = Enumerable
  44.                   .Range(0, 50)
  45.                   .Select(currentItem => ReturnDifferenceA()).ToList();
  46. averageA = differenceListA.Average();
  47.  
  48. differenceListB = Enumerable
  49.                   .Range(0, 50)
  50.                   .Select(currentItem => ReturnDifferenceA()).ToList();
  51. averageB = differenceListB.Average();
clone this paste RAW Paste Data