external vs internal linkage and performance
let's say i have 3 functions inside a class :
class Foo {
inline void FooInline() { /* bla bla */ }
static void fooStatic();
void foo()开发者_开发知识库;
};
as i understand the last two have external linkage while the first have internal.
i want to know which function will be the fastest to call to , and what's the tradeoff.
thanks
No, all three have external linkage. Member functions of a non-local class always have external linkage in C++. Moreover, inline
has no effect on linkage, even if it is a non-member function.
Linkage has no effect on efficiency. Inlining might have, but it depends on too many variables.
just to be clear.
class fooClass
{
inline void fooInline() { /*blah blah*/ }
static void fooStatic() { /*blah blah*/ }
void foo() { /*blah blah*/ }
};
As noted elsewhere. inline
has no affect on linkage. Also static
used as above in a method declaration/definition does not carry any linkage semantics. static
is unfortunately an over used as a keyword. It effects linkage when used on global/namespace scope variables/functions. It has a totally different meaning when applied to class methods.
As for your question they all have external linkage. They all have the same performance when called. The inline MIGHT have and advantage IF the other two function are defined in a cpp file instead of the class AND the compiler decides it will be faster to inline calls to fooInline
. fooInline
will have no advantage in the source file where foo
and fooStatic
are defined.
All of this sounds like premature optimization. There are other problems worth tackling that will make your code much faster.
inline
doesn't have "linkage" per say, it usually (though the compiler does not have to comply) just puts the code literally, uhh, inline.
You see internal linkage with anonymous namespaces and (standalone, not class) static functions, e.g.
namespace
{
void foo() { ... }
}
Or:
static void foo() { ... }
Internal linkage means that the compiler can do some extra optimization (because it knows exactly how the function is being used) and doesn't have to create an exported symbol, which means less relocations on startup (meaning faster startups -- though modern linkers do lazy symbol resolution...)
The second one has internal linkage since you declared it static. It can be referenced only in the same translation unit.
精彩评论