开发者

Speeding up code - 3D array

开发者 https://www.devze.com 2023-01-25 05:50 出处:网络
I\'m trying to improve the speed of some code I\'ve written. I was wondering how efficient accessing data from a 3d array of integers is?

I'm trying to improve the speed of some code I've written. I was wondering how efficient accessing data from a 3d array of integers is?

I have an array

int cube[][][] = new int[10][10][10];

which I populate with values. I then access these values several thousand times.

I was wondering, seeing as all 3d arrays are theoretically stored in 1D arrays in memory, is there a way to turn my 3d array into a 1d one? For instance I could have cube[0] referring to the old cube[0][0][0] and cube [1] refering to the 开发者_如何转开发old cube[0][0][1].

I'm not sure how to go about doing it. I'm sure it's possible but my brain is worn out.

Thanks


You can create the single-dimension array as follows:

int cube[] = new int[w * h * d];

And to access an element:

int value = cube[x * h * d + y * d + z];

But I doubt it will be much faster and you're losing some convenience and safety. Before deciding to go through with this change it might be a good idea to perform some benchmark tests on your data to see if you actually have a problem and whether the change gives a sufficiently large improvement to be worth the extra complexity.


That's exactly what Java is doing behind the scenes. A three dimensional array is simply an array of arrays of arrays. In theory you could separate the arrays into 10 two dimensional arrays or 100 one-dimensional arrays (and even into 1000 individual variables), but it would be unlikely to speed up your performance. Focus on optimizing your algorithm instead.


int cube[] = new int[ X*Y*Z ];
cube[ i*X*Y + j*X + k ] = ...

But, as others already said: It's not expected to be faster (as the calculations have to be done anyway). Let Java do its stuff for reasons of error-avoidance.


Do not do it - Java handles all this for you. You can of course make it a 1D array and then do the calculations but you will hardly beat the optimized JVM code which does the same on the background. Also - is this really causing a performance bottleneck according to a profiler? If not, you might optimize your code prematurely.


You could use a LinkedList and store a 2D array in each Node. That would be more efficient I believe.

0

精彩评论

暂无评论...
验证码 换一张
取 消