Short-Circuiting String Comparison

Short-Circuiting String Comparison

Normally, you don’t need to implement operator == for comparing string objects, as it’s already defined for you. However, for certain applications, you might need to provide a different version of this operator, e.g., when you want to perform a case-insensitive comparison or if you use special collating rules. In German, for instance, umlaut characters and their non-umlauted counterparts have the same lexicographic rank, but their ASCII values are nonetheless different.

You can short circuit the comparison process by first checking whether the two strings have the same length. Obviously, if the lengths differ, there’s no reason to compare the characters one by one. instead, compare the strings character by character only if the lengths are identical. Remember that string::length() is a constant time operation that merely returns a local variable; therefore, this short-circuit technique can provide a significant boost especially when comparing long strings.


Share the Post: