Fast Creation of Objects Instead of Activator.Createinstance(Type)

Instantiate a class with its type

You could use generics.

T MyActivator<T>() where T : new() { return new T(); }

T MyActivator<T>(T variable) where T : new() { return new T(); }

The first one is used if you know the type (explicitly use the type).

The second one is used to infer the type from a variable:

MyType blah = MyActivator<MyType>();

SomeType someVar;
object blah = MyActivator(someVar);

Activator.CreateInstance Performance Alternative

Use a compiled lambda if you can, its MUCH faster.

https://vagifabilov.wordpress.com/2010/04/02/dont-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions/

How to pass type dynamically to Activator.CreateInstance(object)?

It's a bit unclear from the code what the actual intent is, but you can try adjusting your validator's run method to take a generic type like this:

public partial class ValidationRule
{
public void Run<T>(Ctx context, List<ForecastViewModel> entity)
where T : class, INewReleaseValidationEntity
{
var execution = (T)Activator.CreateInstance<T>();
execution.Run(context, entity.ToArray());
}
}

And call it like this:

new ValidationRule().Run<CustomerAssociation(context, entities);

Activator.CreateInstanceT Vs new

This overload of the "Activator.CreateInstance" method is used by compilers to implement the instantiation of types specified by type parameters using generics.

Say you have the following method:

public static T Factory<T>() where T: new()
{
return new T();
}

The compiler will convert the "return new T();" to call "CreateInstance".

In general, there is no use for the CreateInstance in application code, because the type must be known at compile time. If the type is known at compile time, normal instantiation syntax can be used (new operator in C#, New in Visual Basic, gcnew in C++).

More Info: http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx

How to create a new object instance from a Type

The Activator class within the root System namespace is pretty powerful.

There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

or (new path)

https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance

Here are some simple examples:

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");

How to use Activator.CreateInstance to reflect a type whose constructor parameter differs only by ref

In order to match the ref int x parameter, you can create an instance using Type.GetConstructor and passing it an System.Int32& as a parameter:

var ctor = typeof(SomeType).GetConstructor(new[] { Type.GetType("System.Int32&") });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);

Edit:

As @mikez suggested, it is even better to use typeof(int).MakeByRefType() instead of System.Int32&:

var ctor = typeof(SomeType).GetConstructor(new[] { typeof(int).MakeByRefType(); });
var constructorParameters = new object[] { 1 };
SomeType someType = (SomeType)ctor.Invoke(constructorParameters);

Purpose of Activator.CreateInstance with example?

Say you have a class called MyFancyObject like this one below:

class MyFancyObject
{
public int A { get;set;}
}

It lets you turn:

String ClassName = "MyFancyObject";

Into

MyFancyObject obj;

Using

obj = (MyFancyObject)Activator.CreateInstance("MyAssembly", ClassName))

and can then do stuff like:

obj.A = 100;

That's its purpose. It also has many other overloads such as providing a Type instead of the class name in a string. Why you would have a problem like that is a different story. Here's some people who needed it:

  • Createinstance() - Am I doing this right?
  • C# Using Activator.CreateInstance
  • Creating an object without knowing the class name at design time

.NET 2.0: Activator.CreateInstance(...) vs new: Why is execution speed order-dependent?

Buried in the following article is the cause:

A curious subtlety about how CLR does interface dispatch on array types

The specific text of interest is the following:

Our interface dispatch logic has an important optimization where FOR EACH CALL SITE, it checks one particular target explicitly, and if that fails, does slower hash table lookup, and if that lookup fails, fall back to an expensive lookup. Thus for calls sites that tend to go to one destination it is very fast, and call sites that go to many targets, you get good, but not as great performance.

The call site optimization is initialized according to the concrete type of the first object that appeared.

You should be able to produce a fair comparison by replacing the IPlugin interface in your test with a PluginBase class.



Related Topics



Leave a reply



Submit