Funny, I get exactly the inverse behavior both in debug and release ... ?!
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { const int Count = 1000000; DateTime now = DateTime.Now; for (int i = 0; i < Count; i++) { MyReferenceType t = Activator.CreateInstance<MyReferenceType>(); } Console.WriteLine("typed ref:\t {0}", DateTime.Now.Ticks - now.Ticks); now = DateTime.Now; for (int i = 0; i < Count; i++) { MyReferenceType t = (MyReferenceType) Activator.CreateInstance(typeof(MyReferenceType)); } Console.WriteLine("untyped ref:\t {0}", DateTime.Now.Ticks - now.Ticks); now = DateTime.Now; for (int i = 0; i < Count; i++) { MyValueType t = Activator.CreateInstance<MyValueType>(); } Console.WriteLine("typed val:\t {0}", DateTime.Now.Ticks - now.Ticks); now = DateTime.Now; for (int i = 0; i < Count; i++) { MyValueType t = (MyValueType) Activator.CreateInstance(typeof(MyValueType)); } Console.WriteLine("untyped val:\t {0}", DateTime.Now.Ticks - now.Ticks); Console.ReadKey(); } class MyReferenceType { public int dummy; } struct MyValueType { public int dummy; } } } On 2/28/07, Frans Bouma <[EMAIL PROTECTED]> wrote:
I was benchmarking some type instantiation code, and I stumbled upon this: when I instantiate in a loop 1,000,000 times a class with the code: MyType t = Activator.CreateInstance<MyType>(); it takes 2800ms or thereabout. When I use: MyType t = (MyType)Activator.CreateInstance(typeof(MyType)); it takes 330ms or thereabout (debug builds). why this big difference? The code internally (peeking with reflector) shows two different code paths, though I then wonder, why isn't Activator.CreateInstance<T> implemented as: public T CreateInstance<T>() { return (T)Activator.CreateInstance(typeof(T)); } ? FB =================================== This list is hosted by DevelopMentor(r) http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com
-- Sébastien www.sebastienlorion.com