I have a very long code, which is being called millions of time, I have noticed that if I change all the macros into inline functions the code runs a lot faster.
Can you explain why this is? Aren't macros only a text replacement? As opposed to inline functions which can be a call to a function?
A macro is a text sustitution and will as such generally produce more executable code. Every time you call a macro, code is inserted (well, not necessarily, the macro could be empty... but in principle).
Inline functions, on the other hand, may work the same as macros, but they might also not be inlined at all.
In general, the inline
keyword is rather a weak hint than a requirement anyway, compilers will nowadays judiciously inline functions (or will abstain from doing so) based on heuristics, mostly the number of pseudo-instructions.
Inline functions may thus cause the compiler to not inline the function at all, or inline it a couple of times and then call it non-inined in addition.
Surprisingly, not inlining may actually be faster than inlining, since it reduces overall code size and thus the number of cache and TLB misses.
This will depend on the particular macro and function call that you are using. A particular macro can actually compile to a longer set of operations than the inline function. It is often better not to use a macro for certain processes. The inline function will allow the compiler to type check and optimize the various processes. Macros will be subject to a number of errors and can actually cause various inefficiencies (such as by having to move variables in and out of storage).
In any case, since you actually see this happening in your code, you can tell that the compiler is able to optimize your inline code rather than blindly put in the text expansion.
Note that a google search 'macros vs inline' shows a number of discussions of this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With