Just writing a simple string tokeniser from scratch, when I came to a "clever" realisation when it comes to bounds checking.
Say you have a string of a certain length, and you want to find a token within a section of the string, you would provide an index for the first character position you want to search from and another index for the last character in the string you will be looking.
Then you need to verify the sanity of these values.
The immediate way to do that would be to just check each first and last bounds to the length of the string and check that the last bound index is not before the first.
Then I came up with the following optimisation:
static inline int findToken(const int firstIndexInclusive, const int lastIndexExclusive,
const std::string string, const std::string oneOfChars) {
unsigned long stringLength = string.length();
if ((firstIndexInclusive < 0) || (lastIndexExclusive > stringLength) || (lastIndexExclusive < firstIndexInclusive)) {
return -1;
}
//searching for occurence of any of the 'oneOfChars' here
return 0;
}
Just three tests accounts for all the boundaries that you would normally check against, which in normal cases I would probably have 5 checks for.
After the first bit of cleverness subsided, it came to me that the readability goes down, the optimisation is rather minor unless if I process a lot of text, although the time I spent making this was not much. Besides, I think that if you do obvious optimisations while you write code, that is a good thing, but the readability factor is an issue to me.
What do you think? Is this premature optimisation?