Important: Please read the Qt Code of Conduct -

Faster to create new variable or reuse existing one for math calculation?

  • Hello,

    So I have a question that sprung out of curiosity as I was programming; is it better to reuse an existing variable or create a new variable for the following situation:

    /* Is this faster: */

    QMatrix4x4 newViewModelMatrix = (*existingViewMatrix) * (*existingModelMatrix);

    /* Or is this faster? */

    QMatrix4x4 existingViewModelMatrix; /* declared in class header - initial value assigned in class constructor */

    existingViewModelMatrix = (*existingViewMatrix) * (*existingModelMatrix);

    Just wondering if it makes a difference or not.

    Thank you.

  • [quote author="tmason101" date="1423836336"]
    /* Is this faster: */

    QMatrix4x4 newViewModelMatrix = (*existingViewMatrix) * (*existingModelMatrix);
    Yes, this is better in pretty much every way.

    This way the matrix gets created on the stack, or may even be put entirely in CPU registers. The stack/registers is generally the hottest place (in level 1 cache) you can have variables.

    Since the matrix multiplication changes every cell of the matrix, the compiler removes the code that initializes the matrix in the constructor. The compiler can't do that for your class member.

    Whenever in doubt it can be useful to check the assembly code generated by the optimizing compiler. As always, beware of premature optimization.

    PS. It is possible to think of a scenario where the matrix has to be put onto the stack and the stack isn't a hot memory location: When this function is called when the stack is at its deepest and this memory location doesn't get to stay in cache between calls to the function.

  • Thank you, I have been doing a few things wrong then :)

  • Lifetime Qt Champion


    Out of curiosity, why are you using pointers for existingViewMatrix and existingModelMatrix ?

  • Hey,

    The existingViewMatrix pointer above in the example code represents the camera matrix; in the spectrum of the larger project that represents where my camera is, what it is looking at, etc.

    Therefore, from what I see I keep only one instance of that existingViewMatrix object in memory and in different places I point to it when needed for reading or updating.

    The existingModelMatrix pointer represents the position, translation, scaling, and rotation of the OpenGL mesh I am drawing.

    Again, I saw it fit to have the matrix representing that information only once in memory and use a pointer for reading and updating that information.

    If there is a better way which results in faster rendering I am open to it!

    Thank you.

Log in to reply