考虑这个简单的类
public class MyData
{
public int Count;
}
还有这个不喜欢数字10的简单方法。
public bool IsDataValid(MyData data)
{
return consumerData is not { Count: 10 };
}
模式匹配过程中是否发生对象分配? 模式匹配是否会导致上述检查的性能低于
consumerData != null && consumerData.Count != 10
?
我们可以通过 Sharplab 运行代码,看看会发生什么;如果我们使用 C# 输出,我们可以看到有效的代码:
public bool IsDataValid(MyData data)
{
return data == null || data.Count != 10;
}
所以:没什么可怕的。我们还可以看看IL:
.method public hidebysig
instance bool IsDataValid (
class MyData data
) cil managed
{
.custom instance void System.Runtime.CompilerServices.NullableContextAttribute::.ctor(uint8) = (
01 00 01 00 00
)
// Method begins at RVA 0x20a5
// Code size 20 (0x14)
.maxstack 8
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000f
IL_0003: ldarg.1
IL_0004: ldfld int32 MyData::Count
IL_0009: ldc.i4.s 10
IL_000b: ceq
IL_000d: br.s IL_0010
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ceq
IL_0013: ret
} // end of method P::IsDataValid
这只是一些分支和比较 - 没有
newobj
或 box
;都好。没有分配。 C# 编译器团队尝试非常高效地完成任务。