One NxM array or N arrays of size M?

200 views Asked by At

I'm running a scientific computation and need to store velocities of particles. To store the 3 components, should I use 3 different arrays or single 1x3 array? Will it affect my computation in any way?

My number of particles will be large, may even go up to 1e10 or more. I will be using C++.

1

There are 1 answers

5
Dimitar On

Always try to firstly write readable and maintainable code and only then optimize.

In C++, as in in the good old C, memory is allocated in one big chunk (min. is 10240 bytes) internally by brk or sbrk. So imagine that you have previously allocated and freed some memory.

Case 1: You create 3 arrays. Most probably, there would be some free chunks among the used ones. So it would basically iterate over the list of free chunks and place them according to the algorithm, probably best-fit (but not only). Either way, it would (or could, since it's runtime there is no distinct answer) scatter them over the already allocated memory. Say 1 is in the middle, then the other two are in the end.

Case 2: You create 1 array. Then it would be allocated at one place. Either newly acquired storage or available one.

So I would go with the 1x3 2-dimensional array. That way you would benefit from the locality of reference principle, specifically memory locality.

However,as I said, you should be sure that using the 2-dimensional array won't hurt readability in terms of connectivity of the data.

I hope this sheds some light!