Advertisement
Guest User

Untitled

a guest
Jun 24th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. void Main()
  2. {
  3.     var iterations = 10000000;
  4.     var foos = new Foo[iterations];
  5.  
  6.     var repeats = 10;
  7.  
  8.     var factories = new Func<Foo>[]
  9.     {
  10.         () => new Foo(),
  11.         () => (Foo)Activator.CreateInstance(typeof(Foo)),
  12.         () => FooBar<Foo>.Create(),
  13.     };
  14.  
  15.     var timestamps = new double[factories.Length + 1];
  16.     var durations = new double[factories.Length];
  17.    
  18.     foreach (var factory in factories)
  19.     {
  20.         factory();
  21.     }
  22.    
  23.     var sw = Stopwatch.StartNew();
  24.  
  25.     GC.Collect();
  26.     GC.WaitForPendingFinalizers();
  27.            
  28.     for (int repeat = 0; repeat < repeats; repeat++)
  29.     {
  30.         var cc0 = GC.CollectionCount(0);
  31.         for (int f = 0; f < factories.Length; f++)
  32.         {
  33.             timestamps[f] = sw.Elapsed.TotalMilliseconds;
  34.             for (int i = 0; i < iterations; i++)
  35.             {
  36.                 foos[i] = factories[f]();
  37.                 //factories[f]();
  38.             }          
  39.         }
  40.         timestamps[factories.Length] = sw.Elapsed.TotalMilliseconds;
  41.         for (int i = 0; i < 3; i++)
  42.         {
  43.             durations[i] += timestamps[i + 1] - timestamps[i];
  44.         }
  45.         Console.WriteLine(GC.CollectionCount(0) - cc0);
  46.     }
  47.     for (int i = 0; i < 3; i++)
  48.     {
  49.         Console.WriteLine(durations[i] / repeats);
  50.     }
  51. }
  52.  
  53. public class Foo { }
  54.  
  55. class FooBar<T> where T : new()
  56. {
  57.     public static T Create()
  58.     {
  59.         return new T();
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement