Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Aug 11, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date