0

I found this question for C, which discusses the 2d vs 1d array performance.

I would like to know the same for javascript / typescript, as I'm trying to build a lib which involves many matrix operation.

Currently, I'm using 2d array:

export
type Matrix =  Array<Array<number>>;

With this approach, we can access matrix element by m[row][col]

Also, matrix can be implemented using 1d array, something like this:

Class Matrix {
 row: number;
 col: number;
 data: Array<number>;
}

with this approach, we can access matrix element(i, j) by m.data[i*col+row]

which would be better at performance? or maybe there're other solutions for matrix.

Thanks!

jerry
  • 1,196
  • 2
  • 9
  • 21
  • 1
    I've done some tests on this some while back, but I don't remember the exact results. However I can say that it will be highly dependent on what type of Matrix geometry you have. The array of arrays for 1000x1000 will have different performance characteristics than 10x10000 or 10000x10. It also depends on your access patterns, but In general I would say the 1D array approach will be faster. Also consider the Typed arrays for performant numeric matrices. So I guess the answer is, I recommend you test for your self on your data. – visibleman Feb 06 '18 at 02:53
  • thank you for the prompt response, i'm trying both approach, will try to do some benchmark later if i got time – jerry Feb 06 '18 at 03:31

0 Answers0