C++ 中内联函数的好处?

Benefits of inline functions in C++?(C++ 中内联函数的好处?)

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

问题描述

在 C++ 中使用内联函数的优点/缺点是什么?我看到它只会提高编译器输出的代码的性能,但是有了今天优化的编译器、快速的 CPU、巨大的内存等(不像 1980 年< 内存稀缺,所有东西都必须适合 100KB 内存)什么他们今天真的有优势吗?

What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?

推荐答案

内联函数更快,因为您不需要像参数和返回地址那样在堆栈上/从堆栈上推送和弹出内容;但是,它确实会使您的二进制文件稍大一些.

Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.

这有很大的不同吗?对于大多数人来说,在现代硬件上还不够明显.但它可以有所作为,这对某些人来说已经足够了.

Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.

标记内联内容并不能保证它是内联的.这只是给编译器的一个建议.有时这是不可能的,例如当你有一个虚函数时,或者当涉及递归时.有时编译器只是选择不使用它.

Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.

我可以看到这样的情况会产生明显的差异:

I could see a situation like this making a detectable difference:

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);

这篇关于C++ 中内联函数的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 中内联函数的好处?

基础教程推荐