基础 class 中的非虚拟 C# 方法是否仍会产生 vtable 开销?
Do non-virtual C# methods in a base class still incur vtable overheads?
考虑到为实现最佳性能而编写的 C#,我们可以通过两种方式获得基本 class 方法(注意:我们在这里讨论的是无状态 class,没有字段,只有方法):
- 实例 class A 为 class B 的继承/扩展提供了基础 - 通常的模式
- static class A 具有由 "extender" class B
静态调用的静态方法(纯函数)
我喜欢选项A,因为它让关系更清晰。我想知道的是,如果所有这些基础 class 方法都是非虚拟的,即在基础 class A 中它们已经不能被覆盖,是否有 vtable 调用?显然,"non-virtual" 意味着没有,但是如果有任何开销,我想知道。
根据@HansPassant(非常感谢),
Even non-virtual calls to an instance method are made with the exact
equivalent of a virtual call. Giving up a bit of perf for a very nice
guarantee, a NullReferenceException is always raised at the call site.
Diagnosing NRE when this is null is quite ugly.
Only a call to a static method is non-virtual. That includes extension methods btw.
考虑到为实现最佳性能而编写的 C#,我们可以通过两种方式获得基本 class 方法(注意:我们在这里讨论的是无状态 class,没有字段,只有方法):
- 实例 class A 为 class B 的继承/扩展提供了基础 - 通常的模式
- static class A 具有由 "extender" class B 静态调用的静态方法(纯函数)
我喜欢选项A,因为它让关系更清晰。我想知道的是,如果所有这些基础 class 方法都是非虚拟的,即在基础 class A 中它们已经不能被覆盖,是否有 vtable 调用?显然,"non-virtual" 意味着没有,但是如果有任何开销,我想知道。
根据@HansPassant(非常感谢),
Even non-virtual calls to an instance method are made with the exact equivalent of a virtual call. Giving up a bit of perf for a very nice guarantee, a NullReferenceException is always raised at the call site. Diagnosing NRE when this is null is quite ugly.
Only a call to a static method is non-virtual. That includes extension methods btw.