Now I am read the book Inside The C++ Object Model ‘s fourth section and have some question.
An inline function like this:
inline int max(int a, int b)
{
return (a > b) ? a : b;
}
Then, a statement such as the following:
a = max(x, y);
this statement will transformed to a = (x > y) ? x : y;
But the book say when add a local variables to the inline function like this:
inline int max(int a, int b)
{
int maxval = (a > b) ? a : b;
return maxval;
}
It will transformed to
int __max_lv_maxval;
a = (__max_lv_maxval = (x > y) ? x : y), __max_lv_maxval;
And obvious the function’s performance will drop.
My question is Does the compile (such as VC2010,gcc) optimize the inline function and delete the local variables?
That book seems to be assuming the compiler inlines at a source level, this of course totally depends on the compiler. Most will begin inlining at the AST level, where transforms and certain optimizations can and will occur. This all assumes the compiler will inline the code.
If we look at your function, any decent compiler will turn them both into the same IR code, as it will compile the inline function before it is inlined, thus a temporary is required regardless (at IR level). when the IR is then actually inlined, the temporary will be folded away and instead replaced with the assignment destination of the call to
max.When we compile down to machine code, things can change even more, not only can temporaries be removed, but the destination will most likely be a register (in this case), which will have probably been used for on of the source operands as well.
Bottom Line:
This totally depends on your compiler, optimization levels and how it does variable livelyness analysis, value propagation and folding.