Search code examples
c++performanceoptimizationinline-functionscode-size

Is using an inline function as fast as directly writing the function body in the code?


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

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


Solution

  • 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.

    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.

    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.