What are the performance implications of marking methods / properties as virtual?

后端 未结 7 1279
别那么骄傲
别那么骄傲 2020-12-04 14:06

Question is as stated in the title: What are the performance implications of marking methods / properties as virtual?

Note - I\'m assuming the virtual methods will <

7条回答
  •  北海茫月
    2020-12-04 14:49

    On the desktop side it doesn't matter if the method are overloaded or not, they incur a extra level of indirection through the method pointer table (Virtual method table), which means roughly 2 extra memory reads through indirection before the method call compared a non virtual methods on non sealed classes and non final methods.

    [As an interesting fact, on compact framework version 1.0 the overheat is greater as it doesn't use virtual method tables but simply reflection to discover the right method to execute when calling a virtual method.]

    Also virtual methods are far less likely to be candidates for inlining or other optimizations like tail call than non virtual methods.

    Roughly this is the performance hierarchy of method calls:

    Non virtual methods < Virtual Metods < Interface methods (on classes) < Delegate dispatch < MethodInfo.Invoke < Type.InvokeMember

    But none of these performance implications of various dispatch mechanisms don't matter unless you proven it by measuring ;) (And even then the architecture implications, readability etc might have a big weight on which one to chose)

提交回复
热议问题