Search code examples
c++performanceglm-math

Copy function parameter to const local variable


I'm digging in glm library, and found this type of code, also there are some other simmilar stuff. My question is: what is a purpose to copy function parameter to const local variable inside function, like this -- T const a(angle). Is it for some performance benefits?

template<typename T, qualifier Q>
GLM_FUNC_QUALIFIER qua<T, Q> angleAxis(T const& angle, vec<3, T, Q> const& v)
{
    T const a(angle);
    T const s = glm::sin(a * static_cast<T>(0.5));

    return qua<T, Q>(glm::cos(a * static_cast<T>(0.5)), v * s);
}

Solution

  • There’s no purpose.

    This was probably done in a misguided attempt to avoid the indirection of repeatedly accessing angle (which, being a reference, is probably implemented by the compiler as a pointer). Whether this outweighs the cost of a copy is not obvious: if the type T is small and trivially copyable then making a copy is free but for larger types this will in fact incur a nontrivial overhead. On the other hand, the repeated pointer access can often be avoided entirely by the compiler.

    Regardless of these considerations, if that optimisation was the purpose, it would have been more appropriate to pass angle by value instead: first passing by reference and then copying locally truly serves no purpose.