c++optimizationcompiler-optimization

Do C++ compilers eliminate assignment duplications?


If I have an example function like:

void func1(float a, float b, float c)
{
    setA(a);
    setB(b);
    setC(c);                                        
}

Which calls inlined functions:

inline void setA(float a){ m_a = a; m_isValid = false; }
inline void setB(float b){ m_b = b; m_isValid = false; }
inline void setC(float c){ m_c = c; m_isValid = false; }

Should I care about the "m_isValid = false" duplications or the compiler eliminates them by the optimization?


Solution

  • A decent compiler should remove them in this specific case.

    Completing to a full compiling example

    struct Foo {
        float m_a, m_b, m_c;
        bool m_isValid;
    
        void setA(float a){ m_a = a; m_isValid = false; }
        void setB(float b){ m_b = b; m_isValid = false; }
        void setC(float c){ m_c = c; m_isValid = false; }
    
        void func1(float a, float b, float c);
    };
    
    Foo f;
    
    void func1(float a, float b, float c)
    {
        f.setA(a);
        f.setB(b);
        f.setC(c);
    }
    

    g++ in this case compiles func1 to

    _Z5func1fff:
    .LFB3:
        .cfi_startproc
        movl    4(%esp), %eax     ;; loads a
        movb    $0, f+12          ;; clears m_isValid
        movl    %eax, f           ;; stores m_a
        movl    8(%esp), %eax     ;; loads b
        movl    %eax, f+4         ;; stores m_b
        movl    12(%esp), %eax    ;; loads c
        movl    %eax, f+8         ;; stores m_c
        ret
        .cfi_endproc
    

    Note that while it's true that you should keep an eye out about how to design a program if performance is an issue, this kind of micro-level optimization is best done at the end, after measuring where the code is actually losing time.