optimization - Should we prefer temporary variables over user defined variables in c++ -


Let's say that a C ++ function is Fu () which gives the boolean.

I call this function to check the status of a property or to get the result of a function call.

Then what would be the best way to call this type of function.

Method 1:

  bool flag = foo () if (flag) {// some code} other {// and some code}  

Method 2:

  if (foo ()) {// some code} other {// some code}  

My question : The variable using the variable gives the compiler the opportunity to better optimize in general.

First of all, we should remember the comparison of a compiler, It does not matter: syntax does not matter, only words like we can argue that it has symbolic view in terms of code.

In addition, when the adapter plays, it will apply analysis and changes that equivalent symbolic execution in equivalent binary.

Therefore, what is the key to optimizing words are 3 different syntax forms that can be used for a if statement:

  // If with temporary (make ()) {...} else {...} // Already scope with a variable auto var = make (); If (var) {...} else {...} // With a new variable if (auto var = make ()) {...} else {...}  

The latter syntax is desugared for the following:

  {auto var = make (); If (var) {...} else {...}}  

there is a difference: those variables are different.

  • In the temporary case, the if or else block is executed
  • before it expires In the named variable, its lifetime ends, its scope, hereafter to else as

Normally, The length of life should be negligible, i.e. in some cases, where this matter may be: if you have to use it or if the side effects are correct Need to be indexed.

There may be some effect on the emitted code:

  • For an underlying type: It is unlikely that for any effect
  • Type: This can not be clearly optimized
  • For non-POD type: In the destructor, side-effects (such as release memory) may stop optimization

Which other optimization?

Well, the primary optimization that can be applied here stack reuse , whenever the lifetime of an object has expired, then the compiler will see any other object (see) Should be free to reuse your memory space.

If the compiler can not prove the object, its use should be alive due to side effects in its destructor, then this object may have to take more space on the stack. As mentioned, it is impossible that it comes with the underlying types (when optimization is turned on), but unfortunately I would not be surprised with std :: string .


Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -