Prefetching a member variable of an object, accessed via function call

315 views Asked by At

This question was asked today (Prefetching double class member requires casting to char*?), and the accepted solution was to prefetch the return value of a member function, that returned the member variable by reference.

However, it made me curious - if the member is less than a cache-line offset from the start of the object, doesn't the act of calling the member function of the object implicitly load the object into the cache, thus obviating the need for precaching the member? Would it not be more effective to prefetch the object without calling the member function (as suggested in my answer)?

1

There are 1 answers

1
Mark Miller On BEST ANSWER

Doesn't the act of calling the member function of the object implicitly load the object into the cache, thus obviating the need for precaching the member?

Not quite. For example, look at this code.

#include <iostream>
using namespace std;

class DoubleContainer {
public:
    char space[8];
    double double_;
    double* getDoubleAddr();
};

double* DoubleContainer::getDoubleAddr()
{
    return &double_;
}

int main()
{
   DoubleContainer *dc = NULL;
   double* dp = dc->getDoubleAddr();
   cout << dp << endl;
   return 0;
}

It appears that there should be a null pointer error on the line double* dp = dc->getDoubleAddr();, given that dc is NULL. But if you compile and run this, there is usually no exception.

In the assembly code that is built from this, all the object methods, like dc->getDoubleAddr(), are transformed into standard functions with the first parameter being the address of the calling object (in this case, dc). So calling the function does not cause a null pointer exception; the argument is merely 0x0.

Then, in the code, getDoubleAddr returns the address of the double inside the object, given the object's address. There is no need to access memory here - the program already knows the object type and therefore the location of double_. It merely returns the address of the object, plus its eight-byte offset from char space[8], and the program prints out 0x8.