Although this is not the same code and cannot be the same compiler as you, here is some reference data from a rather old test (bench ++ by Joe Orost):
Test Name: F000005 Class Name: Style CPU Time: 7.70 nanoseconds plus or minus 0.385 Wall/CPU: 1.00 ratio. Iteration Count: 1677721600 Test Description: Time to test a global using a 10-way if/else if statement compare this test with F000006 Test Name: F000006 Class Name: Style CPU Time: 2.00 nanoseconds plus or minus 0.0999 Wall/CPU: 1.00 ratio. Iteration Count: 1677721600 Test Description: Time to test a global using a 10-way switch statement compare this test with F000005 Test Name: F000007 Class Name: Style CPU Time: 3.41 nanoseconds plus or minus 0.171 Wall/CPU: 1.00 ratio. Iteration Count: 1677721600 Test Description: Time to test a global using a 10-way sparse switch statement compare this test with F000005 and F000006 Test Name: F000008 Class Name: Style CPU Time: 2.20 nanoseconds plus or minus 0.110 Wall/CPU: 1.00 ratio. Iteration Count: 1677721600 Test Description: Time to test a global using a 10-way virtual function class compare this test with F000006
This specific result is to compile with the 64-bit version of VC ++ 9.0 (VS 2008), but it is quite similar to what I saw from other recent compilers. The bottom line is that a virtual function is faster than most obvious alternatives and very close to the same speed as the only one that beats it (in fact, both are equal within the margin of error). This, however, depends on dense values, as you can see in F00007, if the values โโare sparse, the switch statement produces code that is slower than calling a virtual function.
Bottom line: calling a virtual function is probably the wrong place to look. Refactored code can easily run slower, and even in the best case, it probably won't get enough to notice or care for.
source share