Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of nested loop vs hard coded matrix multiplication

I am reading a book on 2D game programming and am being walked through a 3x3 matrix class for linear transformations. The author has written a method for multiplying two 3x3 matrices as follows.

public Matrix3x3f mul(Matrix3x3f m1)
{
    return new Matrix3x3f(new float[][]
    {
        {
              this.m[0][0] * m1.m[0][0]     // M[0,0]
            + this.m[0][1] * m1.m[1][0]
            + this.m[0][2] * m1.m[2][0],
              this.m[0][0] * m1.m[0][1]     // M[0,1]
            + this.m[0][1] * m1.m[1][1]
            + this.m[0][2] * m1.m[2][1],
              this.m[0][0] * m1.m[0][2]     // M[0,2]
            + this.m[0][1] * m1.m[1][2]
            + this.m[0][2] * m1.m[2][2],
        },
        {
              this.m[1][0] * m1.m[0][0]     // M[1,0]
            + this.m[1][1] * m1.m[1][0]
            + this.m[1][2] * m1.m[2][0],
              this.m[1][0] * m1.m[0][1]     // M[1,1]
            + this.m[1][1] * m1.m[1][1]
            + this.m[1][2] * m1.m[2][1],
              this.m[1][0] * m1.m[0][2]     // M[1,2]
            + this.m[1][1] * m1.m[1][2]
            + this.m[1][2] * m1.m[2][2],
        },
        {
              this.m[2][0] * m1.m[0][0]     // M[2,0]
            + this.m[2][1] * m1.m[1][0]
            + this.m[2][2] * m1.m[2][0],
              this.m[2][0] * m1.m[0][1]     // M[2,1]
            + this.m[2][1] * m1.m[1][1]
            + this.m[2][2] * m1.m[2][1],
              this.m[2][0] * m1.m[0][2]     // M[2,2]
            + this.m[2][1] * m1.m[1][2]
            + this.m[2][2] * m1.m[2][2],
        },
    });
}

If I personally needed to write a method to do the same I would have come up with some nested loop which did all of these calculations automatically, I am assuming that perhaps the author has written it out this way so that people with little math background can follow along easier.

Does this sound like a fair assumption or could a nested loop version of this method possibly cause performance issues when used heavily in a loop where performance is vital?

like image 439
Unl1ght Avatar asked Mar 01 '26 00:03

Unl1ght


1 Answers

I think this is a performance issue. If you use a loop, it will use a lot of jumping orders, since every iteration it needs to check "if cond goto ___". You should read this post on Branch Prediction and also learn a bit on computer architecture to understand how instructions affects performance, in this case I think you might find caching interesting.

like image 182
ZivS Avatar answered Mar 02 '26 14:03

ZivS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!