C#: Virtual Function invocation is even faster than a delegate invocation?

后端 未结 7 2147
梦谈多话
梦谈多话 2021-02-05 13:02

It just happens to me about one code design question. Say, I have one \"template\" method that invokes some functions that may \"alter\". A intuitive design is to follow \"Templ

7条回答
  •  感情败类
    2021-02-05 13:29

    Think about what's required in each case:

    Virtual call

    • Check for nullity
    • Navigate from object pointer to type pointer
    • Look up method address in instruction table
    • (Not sure - even Richter doesn't cover this) Go to base type if method isn't overridden? Recurse until we find the right method address. (I don't think so - see edit at bottom.)
    • Push original object pointer onto stack ("this")
    • Call method

    Delegate call

    • Check for nullity
    • Navigate from object pointer to array of invocations (all delegates are potentially multicast)
    • Loop over array, and for each invocation:
      • Fetch method address
      • Work out whether or not to pass the target as first argument
      • Push arguments onto stack (may have been done already - not sure)
      • Optionally (depending on whether the invocation is open or closed) push the invocation target onto the stack
      • Call method

    There may be some optimisation so that there's no looping involved in the single-call case, but even so that will take a very quick check.

    But basically there's just as much indirection involved with a delegate. Given the bit I'm unsure of in the virtual method call, it's possible that a call to an unoverridden virtual method in a massively deep type hierarchy would be slower... I'll give it a try and edit with the answer.

    EDIT: I've tried playing around with both the depth of inheritance hierarchy (up to 20 levels), the point of "most derived overriding" and the declared variable type - and none of them seems to make a difference.

    EDIT: I've just tried the original program using an interface (which is passed in) - that ends up having about the same performance as the delegate.

提交回复
热议问题