c++ - Pros and cons of 'inline' -
first of all, state facts know 'inline', don't bother restate them.
- an inline function special kind of function definition must available in every translation unit in function used.
- it hint compiler (which free ignore) omit function call, , expand body instead of call.
- the pro know of (2.) may make code faster.
- the con know if (1.) increases coupling bad.
now let's consider templates. if have template library, need provide definitions of function templates in every translation unit, right? let's forget controversial 'export' while, since doesn't solve problem anyway. so, come conclusion there no reason not make template function inline because con of inline know of there priori.
please correct me if wrong. in advance.
the pro know of (2.) may make code faster.
may being operative word. inlined functions may make code paths faster, yes.
but inlined function puts additional pressure on instruction cache on modern cpus. if function large fit in l1 instruction cache, may run slower performing function call (for cpu can optimize prefetching function , return site).
inlining function may put undue pressure on l2 cache - if inlined function used unusually large number of times, code size increase likelihood of cache misses, leading long delays , pipeline stalls cpu twiddles thumbs waiting memory bus something.
inline
far being silver bullet. compilers aggressive optimization ignore inline
hint completely, instead choose functions inline based on heuristics such code size or presence of branches, irrespective of presence or absence of inline
keyword.
the con know if (1.) increases coupling bad.
this i've never heard. "coupling" concept i've heard used when describing high-level relationships of code. it's more issue of maintainability , generality of code. inline
issue of low-level code generation.
as templates, again, aggressively-optimizing compiler inline if heuristics show advantage doing so.
there is, however, link-level issue consider: may need declare function or template inline
(or static
, depending on situation) in order eliminate duplicate symbols @ link time or restrict symbol visibility. is, of course, not optimization.
in summary, don't bother using inline
keyword except when required.
Comments
Post a Comment