本文介绍了使用内联函数是否和在代码中直接编写函数体一样快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass
{
    public:
        MyClass()
        {
            m_dbLoopStart   = 0.0;
            m_dbLoopStop    = 100.0;
            m_dbLoopStep    = 0.001;
        }

        // Which of the following methods complete in a shorter time?

        void Foo1() const   // This one?
        {
            for (double x=m_dbLoopStart; x<=m_dbLoopStop; x+=m_dbLoopStep)
            {
                f(x);
            }
        }

        void Foo2() const   // Or, this one?
        {
            for (double x=m_dbLoopStart; x<=m_dbLoopStop; x+=m_dbLoopStep)
            {
                2.0 * x + 1.0;
            }
        }

    private:
        double m_dbLoopStart, m_dbLoopStop, m_dbLoopStep;

        inline static double f(double x)
        {
            return 2.0 * x + 1.0;
        }
};

Foo1()Foo2()之间,哪个会更快完成?

Between Foo1() and Foo2(), which one would complete faster?

推荐答案

内联函数可能会更快,因为它们避免了函数调用的开销和返回开销.请记住,编译器可能选择不内联函数.

Inline functions may be faster because they avoid the cost of a function call and return overhead. Remember that compilers may choose not to inline functions.

在大多数翻译器中,必须传递函数参数,并为参数和任何函数本地存储分配空间.在返回端,必须删除函数局部变量,并且通常返回一个值.

In most translators, function parameters must be passed and space allocated for the parameters and any function local storage. On the return side, the function local variables must be removed and usually a value returned.

对于简单的函数(例如getter和setter),函数调用和return的开销大于函数中的代码.因此,内联将加快这些功能.

For simple functions, such as getters and setters, the overhead of the function call and return are greater than the code in the function. Thus inlining will speed up these functions.

内联函数还会删除分支指令以调用该函数.这减少了处理器清除指令高速缓存/管线的机会.尽管现代处理器已经实现了减少分支指令负面影响的算法.

Inline functions also remove the branch instruction to call the function. This reduces the chance of the processor clearing out the instruction cache / pipeline. Although modern processors have implemented algorithms to reduce the negative impact of branch instructions.

在我的编程实践中,我内联小型方法(3行或更小).如果出于性能原因要进行内联,请在进行内联之前先进行介绍.

In my programming practices, I inline small (3 line or smaller) methods. If I'm going to inline for performance reasons, I'll profile before inlining.

这篇关于使用内联函数是否和在代码中直接编写函数体一样快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:04