Should i use lookup-lists instead of a lot of multiplication?

in my application I have a very large array of bytes, its a flattened 3 dimensional array, we populate the array using 3 nested for loops (x, y, z) and then we get the values we want by using a little bit of math, most specifically:

To get an index in the array:

return x + z*SizeX + y*SizeX*SizeZ;

and to return the x/y/z coordinates, given an index:

int index = pos;
var y = (ushort) (pos/SizeX/SizeZ);
pos -= y*SizeX*SizeZ;
var z = (ushort) (pos/SizeX);
pos -= z*SizeX;
var x = (ushort) pos;

return new BlockPos(x, y, z, index, this);

First off, I would imagine the second one can be made more efficient, i just don't know how to do it, any help there would be appreciated :P

My main quesion is, would it be faster for me to make a lookup table for the y and x values (populating when the class is loaded) or is it faster to just leave the multiplication in there?

edit This math is called a LOT in some cases, so if it would be faster, even for a longer startup it would make a differance better.


In most languages and architectures, multiplication will become one (or a few) machine instructions. Whilst those instructions may be relatively expensive, they should still be cheaper that performing a lookup operation - and a lookup operation may very well require a multiplication anyway.

E.g. "locate the 4th element of the array" will be

<array base address> + (3 * <array element size>)

The only optimization I'd recommend given your pseudo code is to perform the "constant" operations (e.g. SizeX*SizeZ) once, and store those results.

Need Your Help

Confused about nested resources and authentication in Rails

ruby-on-rails devise associations crud

Let's see if I can explain myself well enough about the doubts I have.

confused about python subprocess inside for loop

python multithreading queue

I am trying to automate some big data file processing using python.