struct Array
{
int* data;
int size;
};
class WidgetSlow
{
int sum;
public:
void SetSum(const Array& arr)
{
sum = 0;
for( int i=0; i!=arr.size; ++i )//read from an int via a pointer - must be done each iteration, because of the write to a member, below:
sum += arr.data[i];//write to an int via a pointer - can invalidate any other int loaded via a pointer
}
};
class WidgetFast
{
int m_sum;
public:
void SetSum(const Array& arr)
{
int sum = 0;
for( int i=0; i!=arr.size; ++i )
sum += arr.data[i];//write to a local does not invalidate other values loaded via pointers
m_sum = sum;
}
};
These two widgets do the same thing. The first one contains several performance pitfalls. The second one doesn't. The "m_" prefix helps make them visible.