泛型编译时评估和方法内联
Generic type compile time evaluation and method inlining
假设我有以下方法:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod<T>(T inputVariable) where T: parentType
{
if(typeof(T) is childType)
{
// do something
}
if(typeof(T) is anotherChildType)
{
// do other things
}
}
我在程序的不同地方使用这个方法,但是当我检查发布版本的 MSIL 时,我看到以下内容:
1.方法没有内联。
2. 但更糟糕的是 - 该方法在运行时评估 inputVariable 的类型(这是预期的 - 请参阅此 link
https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching).
但我希望内联此方法并在编译时评估 inputVariable 的类型。
检查 MSIL 与内联无关,因为这是由 JIT 完成的 - .NET 代码的第二个编译阶段。
MSIL 仍然包含通用代码,不知道 它将与哪些类型一起使用。这就是 .NET 泛型可以跨编译单元工作的原因。
看起来确实很像这根本不应该是通用代码,而是两个具有相同方法名称的重载:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod(childType inputVariable)
{
// do something
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod(anotherChildType inputVariable)
{
// do other things
}
如果您发现自己在通用代码中进行类型检查,这通常表明您为这项工作选择了错误的工具。
假设我有以下方法:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod<T>(T inputVariable) where T: parentType
{
if(typeof(T) is childType)
{
// do something
}
if(typeof(T) is anotherChildType)
{
// do other things
}
}
我在程序的不同地方使用这个方法,但是当我检查发布版本的 MSIL 时,我看到以下内容: 1.方法没有内联。 2. 但更糟糕的是 - 该方法在运行时评估 inputVariable 的类型(这是预期的 - 请参阅此 link https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching).
但我希望内联此方法并在编译时评估 inputVariable 的类型。
检查 MSIL 与内联无关,因为这是由 JIT 完成的 - .NET 代码的第二个编译阶段。
MSIL 仍然包含通用代码,不知道 它将与哪些类型一起使用。这就是 .NET 泛型可以跨编译单元工作的原因。
看起来确实很像这根本不应该是通用代码,而是两个具有相同方法名称的重载:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod(childType inputVariable)
{
// do something
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod(anotherChildType inputVariable)
{
// do other things
}
如果您发现自己在通用代码中进行类型检查,这通常表明您为这项工作选择了错误的工具。