Wednesday, 18 January 2012

Dereferencing array members

The title refers to code like this

iSum += aData[iIndex];

Looking up in an Array (or Vector) requires the code to find the address of the object or value requested then retrieve whatever's at that address. It might also check whether it exists, and whether it is in range (and if not whether it should grow the Array or Vector to accomodate it).

All that takes time, so its important not to do it more than necessary. This is most often seen when looping over a list of objects. It's easy to write code that looks like this:

for (iTrial = 0; iTrial < kNumTrials; iTrial++) {
    iSum += aData[iTrial].iX + aData[iTrial].iY;

but it is much faster to first dereference the object being accessed so this is only done once. E.g.

for (iTrial = 0; iTrial < kNumTrials; iTrial++) {
    v = aData[iTrial];
    iSum += v.iX + v.iY;

This is another optimisation that scales well with code complexity. The bigger classes are, so the more members they have, the more times a a reference like v above can be used. Similarly larger loops with more code contained within benefit more from such an optimisation.

Even in my simple test app (updated again, and included below) the difference is dramatic. Over four lines it is over 12 times slower if this optimisation is not used. (Test 4 compared to Test 1). This is worse that I'd expect, so probably merits further testing. But it is clearly much slower, making this another straightforward optimisation that can provide a significant performance boost.

No comments:

Post a comment