使用内联函数有什么问题? [英] What is wrong with using inline functions?

查看:137
本文介绍了使用内联函数有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然在某些情况下使用内联函数会非常方便,

While it would be very convenient to use inline functions at some situations,

内联函数有任何缺点吗?

Are there any drawbacks with inline functions?

结论

显然,使用内联函数没有错。

Apparently, There is nothing wrong with using inline functions.

但是值得注意以下几点!

But it is worth noting the following points!


  • 内联的过度使用实际上会使程序变慢。根据函数的大小,对其进行内联会导致代码大小增加或减少。内联非常小的访问器函数通常会减小代码大小,而内联非常大的函数则可以大大增加代码大小。在现代处理器上,由于更好地使用了指令高速缓存,因此较小的代码通常可以更快地运行。 -Google指南

内联函数的速度优势随着函数大小的增加而趋于减少。在某些时候,与函数主体的执行相比,函数调用的开销变小,并且失去了好处-来源

The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost - Source

在某些情况下,内联函数可能不起作用:

There are few situations where an inline function may not work:


  • 对于返回值的函数;

  • 对于不返回任何值的函数;如果存在循环,开关或转到语句。

  • 如果函数是递归的。 -来源

  • For a function returning values; if a return statement exists.
  • For a function not returning any values; if a loop, switch or goto statement exists.
  • If a function is recursive. -Source

__ inline 关键字仅在指定了optimize选项后才会内联函数。如果指定了optimize,是否接受 __ inline 取决于内联优化器选项的设置。默认情况下,只要运行优化器,内联选项就会生效。如果指定optimize,则如果要忽略 __ inline 关键字,还必须指定noinline选项。 -来源

The __inline keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not __inline is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the __inline keyword to be ignored. -Source

推荐答案

值得指出的是,内联关键字实际上只是对编译器的提示。

It worth pointing out that the inline keyword is actually just a hint to the compiler. The compiler may ignore the inline and simply generate code for the function someplace.

内联函数的主要缺点是它可以增加可执行文件的大小(取决于实例化的数量)。在某些平台(例如嵌入式系统)上,这可能是个问题,尤其是如果函数本身是递归的。

The main drawback to inline functions is that it can increase the size of your executable (depending on the number of instantiations). This can be a problem on some platforms (eg. embedded systems), especially if the function itself is recursive.

我还建议使内联函数非常小-内联函数的速度优势会随着函数大小的增加而逐渐减少。在某些时候,与函数主体的执行相比,函数调用的开销变小,并且失去了好处。

I'd also recommend making inline'd functions very small - The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost.

这篇关于使用内联函数有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆