Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can overuse in Macros hurt performance?

Tags:

c++

performance

c

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?

like image 837
Gilad Avatar asked Mar 20 '14 20:03

Gilad


2 Answers

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.

like image 192
Damon Avatar answered Oct 06 '22 02:10

Damon


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.

like image 36
sabbahillel Avatar answered Oct 06 '22 02:10

sabbahillel