Search code examples
c++cmacrosinlinepreprocessor

Do macros in C++ improve performance?


I'm a beginner in C++ and I've just read that macros work by replacing text whenever needed. In this case, does this mean that it makes the .exe run faster? And how is this different than an inline function?

For example, if I have the following macro :

#define SQUARE(x) ((x) * (x))

and normal function :

int Square(const int& x)
{
    return x*x;
}

and inline function :

inline int Square(const int& x)
{
    return x*x;
}

What are the main differences between these three and especially between the inline function and the macro? Thank you.


Solution

  • You should avoid using macros if possible. Inline functions are always the better choice, as they are type safe. An inline function should be as fast as a macro (if it is indeed inlined by the compiler; note that the inline keyword is not binding but just a hint to the compiler, which may ignore it if inlining is not possible).

    PS: as a matter of style, avoid using const Type& for parameter types that are fundamental, like int or double. Simply use the type itself, in other words, use

    int Square(int x)
    

    since a copy won't affect (or even make it worse) performance, see e.g. this question for more details.