内联函数,即在编译的时候将函数体替换函数调用,从而不需要将parameter,return address进行push/pop stack的操作,从而加速app的运行,然而,会增加二进制文件的大小。
比如,再源码中:
inline int foo(int a, int b)
{
return a + b;
}
void bar(int a, int b)
{
NSLog(@"%d", foo(a, b));
}
编译过后成为:
void bar(int a, int b)
{
NSLog(@"%d", a + b);
}
问:内联函数和非内联函数有很大不同吗?
答:对硬件硬性不大,但在性能上有影响。
内联函数不能保证编译时候一定是内联的,内联仅仅是告诉编译器请求内联,但编译器不一定内联,比如再调用虚函数,递归(recursion),比如:
inline int aplusb_pow2(int a, int b) {
return (a + b)*(a + b) ;
}
for(int a = 0; a < 900000; ++a)
for(int b = 0; b < 900000; ++b)
aplusb_pow2(a, b);
#define
for
static inline
. This causes the compiler to create the code for the function inline, rather that creating a function call on the stack. See
here
and
here
for more information.