Inefficient string comparison

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: go-best-practices/inefficient-string-comparison

Language: Go

Severity: Info

Category: Best Practices

Description

In Go, it is recommended not to use strings.ToLower(s1) == strings.ToLower(s2) for case-insensitive string comparison. Instead, the strings.EqualFold(s1, s2) function should be used. Here’s why:

  1. Efficiency: Using strings.EqualFold(s1, s2) is more efficient because it avoids unnecessary string allocations. When you use strings.ToLower(s1), it creates a new lowercase string each time it is called. Comparing two lowercase strings using == (equality operator) then requires additional string comparison operations. In contrast, strings.EqualFold(s1, s2) performs a case-insensitive comparison directly without creating additional strings.
  2. Accurate case-insensitive comparisonstrings.EqualFold(s1, s2) is specifically designed for case-insensitive string comparison. It takes into account different languages and ensures accurate results even with non-ASCII characters or special Unicode cases. In contrast, using strings.ToLower might not handle all edge cases correctly or consistently.
  3. Clarity and readability: By using strings.EqualFold(s1, s2), you convey your intention clearly and improve the readability of your code. The function’s name indicates that it performs a case-insensitive comparison, making the code easier to understand for future developers or maintainers.

Therefore, it is recommended to use strings.EqualFold(s1, s2) for case-insensitive string comparison in Go. This approach provides better performance, accuracy, and code clarity.

Non-Compliant Code Examples

func main() {
    if strings.ToLower(s1) != strings.ToLower(s2) {
        //
    }
    if !strings.EqualFold(s1, s2) {
        //
    }
}
func main() {
    if strings.ToLower(s1) == strings.ToLower(s2) {
        //
    }
}

Compliant Code Examples

func main() {
    if strings.EqualFold(s1, s2) {
        //
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: may/unit-testing