I was just thinking is there any performance difference between the 2 statements in C/C++:
Case 1:
if (p==0)
do_this();
else if (p==1)
do_that();
else if (p==2)
do_these():
Case 2:
if(p==0)
do_this();
if(p==1)
do_that();
if(p==2)
do_these();
Assuming simple types (in this case, I used
int) and no funny business (didn’t redefine operator= for int), at least with GCC 4.6 on AMD64, there is no difference. The generated code is identical:The extra instruction at the end of case_1 is just for padding (to get the next function aligned).
This isn’t really surprising, figuring out that p isn’t changed in that function is fairly basic optimization. If p could be changed (e.g., passed-by-reference or pointer to the various
do_…functions, or was a reference or pointer itself, so there could be an alias) then the behavior is different, and of course the generated code would be too.