Interleaving Audio - Best Memory Access approach

Given the following 2 psuedo algorythms for interleaving which approach is best,

float pSamples[numBufferSamples*numBufferChannels];

// read aligned
for(int c=0;c<numBufferChannels;c++) {
for(int s=0;s<numBufferSamples;s++) {
pSamples [ (s*numBufferChannels) + c ] = bufferSamples[c][s];
}
}

// write aligned
for(int s=0;s<numBufferSamples;s++) {
for(int c=0;c<numBufferChannels;c++) {
int sampleOffset = s * numBufferChannels;
pSamples [ sampleOffset + c ] = bufferSamples[c][s];
}
}

  • Read Aligned
  • Write Aligned

0 voters

So the first one is read aligned and the second write aligned. My thought is the write operation is more expensive so that should be aligned. Not sure of the best way to test this and was wondering if there’s a general consensus that one way is better than the other.

(Please use 3 backticks around code so that it shows up nicely on the forum!)

Like almost all performance questions, there’s only one correct answer which is “measure it”!

And like many performance questions, you’ll find that the answer depends on the data. My guess is that if you actually measured this, you’d find that one way is faster with smaller buffers, and the other way faster with larger buffers, and the point at which they cross over depends on the CPU, cache size, compiler, and a million other variables.