fork download
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Collections.Generic;
  5.  
  6. public class Test
  7. {
  8. public static void Main()
  9. {
  10. Random rnd = new Random(123);
  11.  
  12. StringBuilder sb = new StringBuilder();
  13.  
  14.  
  15.  
  16. string text = sb.ToString();
  17. for (int i = 0; i < 1000000; i++) sb.Append((char)(rnd.Next(26) + 63));
  18. text = sb.ToString();
  19.  
  20. double start, linqtime, dictionarytime;
  21.  
  22. start = System.DateTime.Now.Ticks;
  23. var linq = text.GroupBy(c => c);
  24.  
  25. foreach (var a in linq)
  26. {
  27. Console.WriteLine("{0} = {1}", a.Key, a.Count());
  28. }
  29. linqtime = System.DateTime.Now.Ticks - start;
  30.  
  31.  
  32. start = System.DateTime.Now.Ticks;
  33. Dictionary<char, int> counts = new Dictionary<char, int>();
  34. for (int i = 0; i < text.Length; i++)
  35. if (counts.ContainsKey(text[i]))
  36. counts[text[i]]++;
  37. else
  38. counts.Add(text[i], 1);
  39.  
  40. foreach (var count in counts)
  41. Console.WriteLine("{0} = {1}", count.Key, count.Value);
  42.  
  43. dictionarytime = System.DateTime.Now.Ticks - start;
  44.  
  45. Console.WriteLine("LINQ time : {1}\nDictionary time : {2}\nLINQ is {0}% quicker" , dictionarytime/linqtime * 100 - 100, linqtime, dictionarytime);
  46. }
  47. }
Success #stdin #stdout 1.02s 45088KB
stdin
1
2
10
42
11
stdout
T = 38123
E = 38526
H = 38340
N = 38627
R = 38838
V = 38436
B = 38460
U = 38272
P = 38256
@ = 38554
I = 38529
K = 38214
C = 38677
L = 38391
O = 38845
S = 38477
Q = 38153
A = 38628
M = 38440
? = 38081
W = 38213
D = 38610
X = 38009
J = 38741
F = 38832
G = 38728
T = 38123
E = 38526
H = 38340
N = 38627
R = 38838
V = 38436
B = 38460
U = 38272
P = 38256
@ = 38554
I = 38529
K = 38214
C = 38677
L = 38391
O = 38845
S = 38477
Q = 38153
A = 38628
M = 38440
? = 38081
W = 38213
D = 38610
X = 38009
J = 38741
F = 38832
G = 38728
LINQ time : 7551360
Dictionary time : 1823232
LINQ is -75.8555809814391% quicker