You are here:

C++/more efficient?

Advertisement


Question
could you tell me which one is more efficient and why please?

if (a && b) f1(); else f2();
or

if (a)
if (b) f1(); else f2();

Answer
the two forms are not equivalent.

form one is:
 a    b    result
 --  --    ------
 T    T     f1()
 T    F     f2()
 F    T     f2()
 F    F     f2()

form two is:
 a    b    result
 --  --    ------
 T    T     f1()
 T    F     f2()
 F    T     do nothing
 F    F     do nothing

if we rewrite form two as
     if (a)
       if (b) f1(); else f2();
     else f2() ;   


both become equivalent and both are equally efficient. an optimizing compiler would reduce both to the same form.

efficient.cc
------------

void f1() ;
void f2() ;

void function_one( bool a, bool b )
{
   if (a && b) f1(); else f2();
}

void function_two( bool a, bool b )
{
   if (a)
     if (b) f1(); else f2();
   else f2() ;
}


g++ -Wall -std=c++98 -pedantic -Werror -O3 -S -c efficient.cc

efficient.s
-----------

  .file   "efficient.cc"
  .text
  .p2align 2,,3
.globl _Z12function_twobb
  .type   _Z12function_twobb, @function
_Z12function_twobb:
.LFB3:
  pushl   %ebp
.LCFI0:
  movl   %esp, %ebp
.LCFI1:
  movb   12(%ebp), %al
  cmpb   $0, 8(%ebp)
  je   .L2
  testb   %al, %al
  je   .L2
  leave
  jmp   _Z2f1v
  .p2align 2,,3
.L2:
  leave
  jmp   _Z2f2v
.LFE3:
  .size   _Z12function_twobb, .-_Z12function_twobb
  .p2align 2,,3
.globl _Z12function_onebb
  .type   _Z12function_onebb, @function
_Z12function_onebb:
.LFB2:
  pushl   %ebp
.LCFI2:
  movl   %esp, %ebp
.LCFI3:
  movb   12(%ebp), %al
  cmpb   $0, 8(%ebp)
  je   .L7
  testb   %al, %al
  jne   .L9
.L7:
  leave
  jmp   _Z2f2v
  .p2align 2,,3
.L9:
  leave
  jmp   _Z2f1v
.LFE2:
  .size   _Z12function_onebb, .-_Z12function_onebb
  .ident   "GCC: (GNU) 4.3.3 20090101 (prerelease)"

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.