Ulf Kadner wrote:
Hello!
I have read, inline functions are, exactly like macros by the
Preprocessor be implemented directly and therefore offer, due to a
smaller Overheads a certain speed advantage. Did I understand it so
correctly? Why is code implemented by the Preprocessor faster, and/or
why this does not produce so much Overhead?
Think of the following:
You have a function:
double twice( double Argument )
{
return 2 * Argument;
}
In order to call that function, eg. like this
int main()
{
double x;
x = twice( 5.0 );
}
The code has to actually call that function. That means that information
must be stored somewhere from where the call was made, in order to give
the return a chance to find its way back. Also: A new variable 'Argument'
must be created, intialized with the value 5 and destroyed when the function
actually returns. That brings us to the return value. Somehow the return value
(the result of 2 * Argument) must find its way back to the caller. All of this
costs time.
Now the very same thing, but without a function call:
int main()
{
double x;
x = 2 * 10.0;
}
No call is made, no variable needs to be created, no return value must find it's
way back, no return address must be stored somewhere. It is easy to see, that this
is usually way faster then the first version.
Now say, that you don't want the actual computation in main. What options are there.
The old, C way, was to use a macro:
#define TWICE(X) ( 2 * (X) )
int main()
{
double x;
x = TWICE(5.0);
}
when the Preprocessor runs, it substitutes the macro with the text its stands for.
Thus after the preprocessor has done its work, the following is feed to the actual
compiler:
int main()
{
double x;
x = ( 2 * (5.0) );
}
and heureka (!), we are back to the fast version.
Another method would be to use an inline function. This is somewhat similar
in that the compiler (not the preprocessor) is able to replace the actual
call of the function with the function body:
inline double twice( double Argument )
{
return 2 * Argument;
}
int main()
{
double x;
x = twice( 5.0 );
}
Now if the compilers grants your inline request, it internally will modify
your program as if you had written:
int main()
{
double x;
{
double Argument = 5.0;
x = 2 * Argument;
}
}
a few optimizing steps later, this will reduce to:
int main()
{
double x;
x = 2 * 5.0;
}
HTH
--
Karl Heinz Buchegger
kb******@gascad.at