Benefits of inline functions in 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++ 中内联函数的好处?
基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01