C ++ inline function and contextual optimization

I read in Scott Myers' Effective C ++ Book that:

When you embed a function, you can enable the compiler to perform context optimizations in the function body. This optimization is not possible for ordinary function calls.

Now the question arises: what is contextual optimization and why is it needed?

+4
source share
4 answers

I don’t think that “contextual optimization” is a definite term, but I think that it basically means that the compiler can analyze the call site and the code around it and use this information to optimize the function.

. , , :

:

int foo(int i)
{
  if (i < 0) throw std::invalid_argument("");
  return -i;
}

:

int bar()
{
  int i = 5;
  return foo(i);
}

foo , . bar, :

int bar()
{
  int i = 5;
  if (i < 0) throw std::invalid_argument("");
  return -i;
}

int bar()
{
  return -5;
}
+6

, . . .

, :

bool callee(bool a){
   if(a) return false;
   else return true;
}

void caller(){
   if(callee(true)){
       //Do something
   }   
   //Do something
}

():

void caller(){
   bool a = true;
   bool ret;
   if(a) ret = false;
   else ret = true;

   if(ret){
       //Do something
   }   
   //Do something
}

:

void caller(){
   if(false){
       //Do something
   }   
   //Do something
}

:

void caller(){
   //Do something
}

, ( ) .

+2

,

void fun( bool b) { if(b) do_sth1(); else do_sth2(); }

false

bool param = false;
...
fun( param);

...
do_sth2();
+2

, - , , , .

getter , :

  • (eax on x86 Visual Studio )
  • eax

inlining .

, ( , .. /, .

.

0

Source: https://habr.com/ru/post/1547910/


All Articles