Advertisement
Dr_Asik

Benchmark For vs ForEach

Jan 9th, 2013
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.16 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3.  
  4. namespace PerfTestCSharp {
  5.     class Program {
  6.         static void Main() {
  7.             var collection = new int[100000000];
  8.  
  9.             Benchmark(() => SumForEach(collection), "SumForEach");
  10.             Benchmark(() => SumFor(collection), "SumFor");
  11.            
  12.         }
  13.  
  14.         static long SumForEach(int[] collection) {
  15.             long sum = 0;
  16.             foreach (var i in collection) {
  17.                 sum += i;
  18.             }
  19.             return sum;
  20.         }
  21.  
  22.         static long SumFor(int[] collection) {
  23.             long sum = 0;
  24.             for (int i = 0; i < collection.Length; ++i) {
  25.                 sum += collection[i];
  26.             }
  27.             return sum;
  28.         }
  29.  
  30.         static void Benchmark<T>(Func<T> func, string message) {
  31.             // warm-up call
  32.             func();
  33.  
  34.             var sw = Stopwatch.StartNew();
  35.             for (int i = 0; i < 5; ++i) {
  36.                 var res = func();
  37.                 Console.Write(res);
  38.             }
  39.             Console.Write('\n');
  40.             Console.WriteLine(message + " : {0} ms", sw.ElapsedMilliseconds);
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement