To accommodate unit testing and mocking it's become a common practice to declare methods and properties as virtual. Is there a performance impact of declaring something virtual as supposed to non-virtual?
Virtual functions are by definition slower than their non-virtual counterparts; we wanted to measure the performance gains from inlining; using virtual functions would make the difference even more pronounced.
Static methods are 68 times faster than virtual methods. Virtual methods are 10.5 times slower than instance methods.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. Functions are declared with a virtual keyword in base class.
A virtual call requires at least an extra indexed dereference and sometimes a "fixup" addition, compared to a non-virtual call, which is simply a jump to a compiled-in pointer. Therefore, calling virtual functions is inherently slower than calling non-virtual functions.
In general, the difference is that virtual methods are called using a Callvirt Opcode, whereas not virtual methods use a standard Call Opcode. Call Opcodes are definitely faster than Callvirt, but I've never ever every found it nearly substantial enough to justify making design decisions based on this.
Premature optimization is the root of all evil.
Nope, not really.
It is not something you are going to notice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With