Tuples inside an Array

I have this app where in one method I create an array of UInt64 pairs of values, and store them consecutively in the array. Then this array is passed to, and used, in another method which uses these values, and updates and stores them back into the array.

For example, if the Array has n elements (always known beforehand), then let’s say the values represent a left and right pair (l, r). I store them consecutively as ary[0] = l1; ary[1] = r1, ary[2] = l2, ary[3] = r2, etc. Then in the method that uses them they are read out, and put back, in the same order.

But this requires 2 writes for each pair, and when they are used, it requires 2 reads to use the values, and 2 write to put back the updated values.

So I was thinking (ominous practice) that maybe it would be faster and/or more memory efficient to store them as a tuple {l, r} for each memory location, and then when I use them I can do just one memory read and write like this. (This would also make the code conceptually simpler to read and understand, because it would be clearer that these 2 values should be considered a pair that are always processed together):

l, r = arry[i]

......

ary[i] = {l', r'}

and save a memory read and write.

So… is this possible the way I described, and would it really be of substantial benefit, in terms of performance increase or mem efficiency (I DO NOT want to create a 2D array)?

At that point you’d be better off just doing Array(Pair), where Pair is record Pair, left : UInt64, right : UInt64. Would be even easier to read versus using array access. I guess one question I have, I assume you’re putting them back into the array because the values changed?

It does not “save a memory read and write”, because reading or writing that Tuple itself ultimately incurs the same number of operations. On release mode they do the same thing.

In most cases the memory layout of Tuple(T, T) should be the same as two Ts laid contiguously together.

4 Likes