我知道在 C# 中创建对象的一种方法:
public static class ObjectCreator
{
public static T GetObject<T>() where T : class
{
return (T)Activator.CreateInstance(typeof(T));
}
}
有没有更高产的?
用已知方式更新类:
public class ObjectCreator<T> where T: new()
{
protected Func<T> V4Lambda;
protected Func<T> V5Lambda;
public ObjectCreator()
{
Type sType = typeof(T);
//V4
V4Lambda = Expression.Lambda<Func<T>>(Expression.New(sType)).Compile();
//V5
V5Lambda = DynamicModuleLambdaCompiler.GenerateFactory<T>();
}
public T V1()
{
return (T)Activator.CreateInstance(typeof(T));
}
public T V2()
{
return new T();
}
public T V3()
{
return CustomActivator.CreateInstance<T>();
}
public T V4()
{
return V4Lambda();
}
public T V5()
{
return V5Lambda();
}
}
public static class CustomActivator
{
public static T CreateInstance<T>() where T : new()
{
return ActivatorImpl<T>.Factory();
}
private class ActivatorImpl<T> where T : new()
{
private static readonly Expression<Func<T>> _expr = () => new T();
public static readonly Func<T> Factory = _expr.Compile();
}
}
public static class DynamicModuleLambdaCompiler
{
public static Func<T> GenerateFactory<T>() where T : new()
{
Expression<Func<T>> expr = () => new T();
NewExpression newExpr = (NewExpression)expr.Body;
var method = new DynamicMethod(
name: "lambda",
returnType: newExpr.Type,
parameterTypes: new Type[0],
m: typeof(DynamicModuleLambdaCompiler).Module,
skipVisibility: true);
ILGenerator ilGen = method.GetILGenerator();
// Constructor for value types could be null
if (newExpr.Constructor != null)
{
ilGen.Emit(OpCodes.Newobj, newExpr.Constructor);
}
else
{
LocalBuilder temp = ilGen.DeclareLocal(newExpr.Type);
ilGen.Emit(OpCodes.Ldloca, temp);
ilGen.Emit(OpCodes.Initobj, newExpr.Type);
ilGen.Emit(OpCodes.Ldloc, temp);
}
ilGen.Emit(OpCodes.Ret);
return (Func<T>)method.CreateDelegate(typeof(Func<T>));
}
}
我的测试结果:

在 Sergei Teplyakov 的以下文章中
它得出的结论是,创建对象的最快方法是将 lambda 解析为表达式并编译它:
您几乎不应该进行低级微优化。(因为编译器迟早会优化得更好。)
但是如果在某些地方你真的需要优化,那么只需将创建函数传递到
Func<T>你需要的地方就足够了,就是这样:你会失去一些抽象,但你应该去,而不是跳棋?这是最快的方法。
在正确的地方调用正确的构造函数会更快。因为调用代表不是免费的。另一方面,如果您需要纳米优化,那么您选择了错误的平台。
基准: