user8387109
user8387109

Reputation:

Increase Array access speed

Right now I am optimizing my code but I am really stuck. I tracked down the time needed to run several commands and came to the conclusion that accessing a 3 dimensional array 'costs' the most time.

array1 is [Struct Data type], array2 is [[[UInt8]]]

I use:

for a in 0 ..< 600 {
    for b in 0..< 900 {
        array1[counter] = Struct(s:array2[var1][var2][var3])
    }
}

I used:

for a in 0 ..< 600 {
    for b in 0..< 900 {
         array1[counter] = Struct(s:UInt8(123))
    }
}

which got me a huge boost but is useless. I therefore concluded that accessing array2 takes most time. The loop which includes the first sample runs in 0.025 Seconds and the second in 0.005 Seconds.

How can I access a 3 dimensional array faster? I tried to make it into an 1 dim array which caused a lot of trouble because it is not explicit which index to use. It also isn't quite faster as I use Swift 4 which already has optimization. Thank you very much for all your help!

Upvotes: 0

Views: 272

Answers (1)

Imran
Imran

Reputation: 13458

If you want to represent a 3d array of dimensions (nX,nY,nZ) as a 1d array use this conversion:

a_3d[x][y][z] <-> a_1d[nY*nX*z + nX*y + x]

For example for a 3x4x5 array:

a_3d[1][2][3] corresponds to a_1d[4*3*3+3*2+1] = a_1d[43]

Upvotes: 3

Related Questions