Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't inline premature optimization? [duplicate]

Possible Duplicate:
Inline functions in C++

Modern compilers are better than programmers at deciding what should be inlined and what should not. Just like, register, shouldn't inlining functions be a job for the compiler only, and be considered premature optimization ?

like image 543
fouronnes Avatar asked Dec 29 '22 00:12

fouronnes


2 Answers

inline has a double meaning that some are unaware of - it allows a function to be defined in more than one translation unit (i.e. if you define an unbound function in a header and include it from within various translation units, you are forced to declare it inline or the linker would complain about doubly defined symbols).

The second meaning is a hint to the compiler that this function may profit from inlining its machine code at the caller site. You're right, modern compilers/optimizers should be able to figure this out on his own.

My advice is to use inline only when it is needed (first case) and never to pass an optimization hint to the compiler. This way, this crazy double meaning is resolved in your source code.

like image 68
Alexander Gessler Avatar answered Jan 07 '23 11:01

Alexander Gessler


inline is only tangentially related to optimization.

You should choose to apply inline to a function if you need the exceptions to the one definition rule that it gives you, and leave it out if you don't. Most of the time you can rely on the compiler to perform the appropriate optimizations independent of whether a function is declared inline or not.

like image 23
CB Bailey Avatar answered Jan 07 '23 10:01

CB Bailey