I'm trying to optimize accessing and changing data of a 3D environment, because some operations have to be done millions of times. Currently I have the following optimizations in place:
- Using a flat array (1D)
- The dimensions are in powers of 2
- Bit-shifting, where possible, instead of multiplication/division
The indexing of the 3D vectors is as follows:
- A change in the X vector would increase/decrease the index by 1
- A change in the Y vector would increase/decrease the index by 3DEnvironmentSize.X
- A change in the Z vector would increase/decrease the index by 3DEnvironmentSize.X * 3DEnvironmentSize.Y
Given the following pseudo-code:
mapSize.X = 4
mapSize.Y = 4
mapSize.Z = 2
Xdif = 1
Ydif = mapSize.X = 4
Zdif = mapSize.X * mapSize.Y = 16
Xexponent = log2(Xdif) = log2(1) = 0 (2^0 = 1 = Xdif)
Yexponent = log2(Ydif) = log2(4) = 2 (2^2 = 4 = Ydif)
Zexponent = log2(Zdif) = log2(16) = 4 (2^4 = 16 = Zdif)
One would go from 3D -> 1D given Vector(1,2,1) using the following:
location.X = 1
location.Y = 2
location.Z = 1
shiftIndex.X = location.X << Xexponent = 1 << 0 = 1
shiftIndex.Y = location.Y << YExponent = 2 << 2 = 8
shiftIndex.Z = location.Z << Zexponent = 1 << 4 = 16
index = shiftIndex.X + shiftIndex.Y + shiftIndex.Z = 1 + 8 + 16 = 25
As you can see, I'm making use of bit-shifting to increase the processing speed. Now I know how to convert 3D -> 1D using devisions and division remainders with given index 30 like so:
index = 30
location.X = index % mapSize.X
location.Y = (index / mapSize.X) % mapSize.Y
location.Z = ((index / mapSize.X) / mapSize.Y) % mapSize.Z
Is there any way to make use of bit-shifting (or anything else for that matter)here somehow that will make this faster as well? I've been trying to crunch this for some time but I'm unable to crack it, if its even possible in the first place.