Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the cost of using a pointer to member function vs. a switch?
    text
    copied!<p>I have the following situation:</p> <pre><code> class A { public: A(int whichFoo); int foo1(); int foo2(); int foo3(); int callFoo(); // cals one of the foo's depending on the value of whichFoo }; </code></pre> <p>In my current implementation I save the value of <code>whichFoo</code> in a data member in the constructor and use a <code>switch</code> in <code>callFoo()</code> to decide which of the foo's to call. Alternatively, I can use a <code>switch</code> in the constructor to save a pointer to the right <code>fooN()</code> to be called in <code>callFoo()</code>. </p> <p>My question is which way is more efficient if an object of class A is only constructed once, while <code>callFoo()</code> is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a <code>switch</code>?</p> <p>Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. </p> <p>Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload