Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance impact of virtual methods

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?

like image 597
TGH Avatar asked Mar 30 '12 04:03

TGH


People also ask

Are virtual methods slower?

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.

Are virtual methods slow C#?

Static methods are 68 times faster than virtual methods. Virtual methods are 10.5 times slower than instance methods.

What is the purpose of virtual 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.

Why are virtual calls slow?

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.


2 Answers

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.

like image 121
Jeff Avatar answered Nov 07 '22 17:11

Jeff


Nope, not really.

It is not something you are going to notice.

like image 24
leppie Avatar answered Nov 07 '22 16:11

leppie