Hello everyone,
I am attempting to write matrix classes for one of my projects and needed some advice on the best way to implement it.
I see two ways i can implement this easily. First is have a simple row storage for the entire matrix.
1 2
double * mat
mat = newdouble[row*col];
The other approach would be to have something like
1 2 3 4
double **mat;
mat = newdouble*[row];
for(i=0;i<row;++i)
mat[i]=newdouble[col];
My question is, which of these two are expected to give a faster access to
the members. Should my choice of the approach depend on the size of the matrix ?
which of these two are expected to give a faster access to the members.
The first one.
pointer to pointer means 2x the indirection which means 2x the overhead.
Should my choice of the approach depend on the size of the matrix ?
In theory, yes. In reality, not really.
A benefit to the "nested new" approach is that the rows don't have to be contiguous in memory. If you have a 10x10 matrix, then you only need 100 contiguous elements, so it's no big deal.
But if you have something ridiculously huge like 100000x100000 matrix, you might have a harder time to allocate contiguous space for the whole matrix, so a nested new might be more successful.
Overall, though, the nested new approach consumes more memory because you have to allocate space for the row pointers as well.
So yeah. Go with the [row*col] approach. Multidimentional arrays are evil.
Thanks for the replies.
Indeed, my primary concern was with the allocation of a large number of contiguous elements.
I expect to have mostly small sized matrices, normally should not be more than 50 x 50, and i suppose i can escape with the first approach. But, i am relatively certain that, eventually, i would be dealing with large matrices, the kinds you encounter in finite element codes, and perhaps, the nested new approach would yield better results then.