Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8497891
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T00:15:16+00:00 2026-06-11T00:15:16+00:00

A friend and I were testing using compiled expressions for object creation instead of

  • 0

A friend and I were testing using compiled expressions for object creation instead of Activator.CreateInstance<T> and ran into some interesting results. We found that when we ran the same code on each of our machines we saw completely opposite results. He got the expected result, significantly better performance out of the compiled expression, whereas I was surprised to see Activator.CreateInstance<T> out perform by 2x.

Both computers ran compiled in .NET 4.0

Computer 1 has .NET 4.5 installed. Computer 2 does not.

Computer 1 over 100000 objects:

45ms - Type<Test>.New()
19ms - System.Activator.CreateInstance<Test>();

Computer 2 over 100000 objects:

13ms - Type<Test>.New()
86ms - System.Activator.CreateInstance<Test>();

And here is the code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;

namespace NewNew
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch benchmark = Stopwatch.StartNew();
            for (int i = 0; i < 100000; i++)
            {
                var result = Type<Test>.New();
            }
            benchmark.Stop();
            Console.WriteLine(benchmark.ElapsedMilliseconds + " Type<Test>.New()");

            benchmark = Stopwatch.StartNew();
            for (int i = 0; i < 100000; i++)
            {
                System.Activator.CreateInstance<Test>();
            }
            benchmark.Stop();
            Console.WriteLine(benchmark.ElapsedMilliseconds + " System.Activator.CreateInstance<Test>();");
            Console.Read();
        }


        static T Create<T>(params object[] args)
        {
            var types = args.Select(p => p.GetType()).ToArray();
            var ctor = typeof(T).GetConstructor(types);

            var exnew = Expression.New(ctor);
            var lambda = Expression.Lambda<T>(exnew);
            var compiled = lambda.Compile();
            return compiled;
        }
    }

    public delegate object ObjectActivator(params object[] args);

    public static class TypeExtensions
    {
        public static object New(this Type input, params object[] args)
        {
            if (TypeCache.Cache.ContainsKey(input))
                return TypeCache.Cache[input](args);

            var types = args.Select(p => p.GetType());
            var constructor = input.GetConstructor(types.ToArray());

            var paraminfo = constructor.GetParameters();

            var paramex = Expression.Parameter(typeof(object[]), "args");

            var argex = new Expression[paraminfo.Length];
            for (int i = 0; i < paraminfo.Length; i++)
            {
                var index = Expression.Constant(i);
                var paramType = paraminfo[i].ParameterType;
                var accessor = Expression.ArrayIndex(paramex, index);
                var cast = Expression.Convert(accessor, paramType);
                argex[i] = cast;
            }

            var newex = Expression.New(constructor, argex);
            var lambda = Expression.Lambda(typeof(ObjectActivator), newex, paramex);
            var result = (ObjectActivator)lambda.Compile();
            TypeCache.Cache.Add(input, result);
            return result(args);
        }
    }

    public class TypeCache
    {
        internal static IDictionary<Type, ObjectActivator> Cache;

        static TypeCache()
        {
            Cache = new Dictionary<Type, ObjectActivator>();
        }
    }

    public class Type<T>
    {
        public static T New(params object[] args)
        {
            return (T)typeof(T).New(args);
        }
    }

    public class Test
    {
        public Test()
        {

        }

        public Test(string name)
        {
            Name = name;
        }

        public string Name { get; set; }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T00:15:17+00:00Added an answer on June 11, 2026 at 12:15 am

    There are at least two causes for this:

    • The overhead of calling Type<Test>.New() or System.Activator.CreateInstance<Test>() for the first time is relatively large. Because of this, I changed 100000 to 10000000.
    • Build your application in release mode, run it without a debugger.

    With those two changes, the two methods take about equally long. On my system, I get between 1100 and 1200 for both methods, sometimes one is a little bit higher, sometimes the other is.

    Note that Activator.CreateInstance<T>() can only call the default constructor, while your New() accepts a number of arguments. If you make your New() less powerful, and always use the default constructor there too, it is slightly faster than Activator.CreateInstance<T>() on my system.

    Note also that your handling of constructors with parameters does not actually work if two different constructors of the same type should be used, depending on the passed arguments. You choose once which constructor to use for the remainder of the entire program.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

My friend is testing my application which uses the SD card to store some
Friends, currently I dont have iphone to test and using Simulator for testing purposes.
I've started working on a new web project with some friends... we are using
This is an error that my friend is getting when testing my app, but
I'm testing my app based on a friend list of about 350 people, and
Hey. I only recently started using Python, and my friend suggested using Twisted as
I'm running into a problem using the SnowBallAnalyzer in Lucene.NET. It works great for
I am trying to send a JSON file to do some testing. I have
friends, while testing application on eclipse using emulator google map is being displayed properly.
Friends, In testing our Oracle Forms application on Vista I have found a interesting

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.