简体   繁体   English

一个NxM阵列还是N个大小为M的阵列?

[英]One NxM array or N arrays of size M?

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? 要存储3个组件,我应该使用3个不同的数组还是单个1x3数组? Will it affect my computation in any way? 它会以任何方式影响我的计算吗?

My number of particles will be large, may even go up to 1e10 or more. 我的粒子数量很大,甚至可能达到1e10或更多。 I will be using C++. 我将使用C ++。

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 . 在C ++中,就像在旧的C语言中一样,内存由brksbrk在一个大块(最小为10240字节)内部分配。 So imagine that you have previously allocated and freed some memory. 因此,假设您先前已经分配并释放了一些内存。

Case 1: You create 3 arrays. 情况1:您创建3个数组。 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. 说1在中间,然后另外两个在最后。

Case 2: You create 1 array. 情况2:您创建1个数组。 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. 因此,我将使用1x3二维数组。 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! 希望这能给您一些启示!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM