Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* output with .NET 4.0 on 2014 beefy machine x86 release build:
- Test1 - Activator.CreateInstance<T>(): 8642
- Test2 - new T() 864
- Test3 - Delegate 1156
- Test4 - Generic new() 8858
- Baseline 327
- */
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- const int IterationCount = 100000000;
- // warmup
- Test1();
- Test2();
- Test3();
- Test4<TestClass>();
- // profile Activator.CreateInstance<T>()
- Stopwatch sw = Stopwatch.StartNew();
- for (int index = 0; index < IterationCount; index++)
- Test1();
- sw.Stop();
- Console.WriteLine("Test1 - Activator.CreateInstance<T>(): {0}", sw.ElapsedMilliseconds);
- // profile new T()
- sw.Restart();
- for (int index = 0; index < IterationCount; index++)
- Test2();
- sw.Stop();
- Console.WriteLine("Test2 - new T() {0}", sw.ElapsedMilliseconds);
- // profile Delegate
- sw.Restart();
- for (int index = 0; index < IterationCount; index++)
- Test3();
- sw.Stop();
- Console.WriteLine("Test3 - Delegate {0}", sw.ElapsedMilliseconds);
- // profile generic new()
- sw.Restart();
- for (int index = 0; index < IterationCount; index++)
- Test4<TestClass>();
- sw.Stop();
- Console.WriteLine("Test4 - Generic new() {0}", sw.ElapsedMilliseconds);
- // profile Baseline
- sw.Restart();
- for (int index = 0; index < IterationCount; index++)
- TestBaseline();
- sw.Stop();
- Console.WriteLine("Baseline {0}", sw.ElapsedMilliseconds);
- }
- public static void Test1()
- {
- var obj = Activator.CreateInstance<TestClass>();
- GC.KeepAlive(obj);
- }
- public static void Test2()
- {
- var obj = new TestClass();
- GC.KeepAlive(obj);
- }
- static Func<TestClass> Create = delegate
- {
- return new TestClass();
- };
- public static void Test3()
- {
- var obj = Create();
- GC.KeepAlive(obj);
- }
- public static void Test4<T>() where T : new()
- {
- var obj = new T();
- GC.KeepAlive(obj);
- }
- static TestClass x = new TestClass();
- public static void TestBaseline()
- {
- GC.KeepAlive(x);
- }
- public class TestClass
- {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement