So we have a custom string class that just wraps a basic C string: char* or a wchar_t*. The only data member of our custom string class is this pointer. Anyways, here at work we are debating adding another member that caches the length of the internal char array. So instead of
MyString::Count { return _tcslen(foo); }
we could just write:
MyString::Count { return m_count; }
But I’m sure there is a special gotcha that would bite us if we did that. You know, some special way to break such an implementation wide open. So my question is, what are the downsides of caching the length?
First thing: don’t do it unless you have profiling data showing this is really a bottleneck. If you don’t have that, you’ve all been wasting your time arguing about this IMO. Make your code correct first, then attack the important bottlenecks.
If you do cache it, make sure all the paths that could modify the internal string also update the
m_countappropriately.If your wrapper hands out a non-const reference or a pointer to the data, don’t cache it – you can’t be certain that the value will remain fixed.