You are here:
ApexGuru Antipattern: Expensive String Comparison
The == operator for string comparison invokes java.text.Collator.compare(), which is slower than using String.equals() or String.equalsIgnoreCase(). Longer strings and larger loops increase overhead.
Scope
Detection and recommendation
Detection Example
apex
if (content.respKey == key) {
// Expensive string comparison
}Recommendation
Use String.equals() for case-sensitive comparisons and
String.equalsIgnoreCase() when ignoring capitalization.
Avoid using == for a string comparison when locale-based
comparison isn’t required. To prevent NullPointerException during comparison, add a null
check.
apex
if (content.respKey != null && content.respKey.equals(key)) {
// Optimized string comparison
}
