Skip to content

Commit

Permalink
strings: faster equality check on simple cases
Browse files Browse the repository at this point in the history
  • Loading branch information
miton18 committed Nov 5, 2024
1 parent bea9b91 commit 32f452a
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions src/strings/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -1185,9 +1185,13 @@ func ReplaceAll(s, old, new string) string {
// are equal under simple Unicode case-folding, which is a more general
// form of case-insensitivity.
func EqualFold(s, t string) bool {
if len(s) != len(t) {
return false
}

// ASCII fast path
i := 0
for ; i < len(s) && i < len(t); i++ {
for ; i < len(s); i++ {
sr := s[i]
tr := t[i]
if sr|tr >= utf8.RuneSelf {
Expand All @@ -1205,22 +1209,15 @@ func EqualFold(s, t string) bool {
}
// ASCII only, sr/tr must be upper/lower case
if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
continue
return false
}
return false
}
// Check if we've exhausted both strings.
return len(s) == len(t)
return true

hasUnicode:
s = s[i:]
t = t[i:]
for _, sr := range s {
// If t is exhausted the strings are not equal.
if len(t) == 0 {
return false
}

// Extract first rune from second string.
var tr rune
if t[0] < utf8.RuneSelf {
Expand Down Expand Up @@ -1256,14 +1253,12 @@ hasUnicode:
for r != sr && r < tr {
r = unicode.SimpleFold(r)
}
if r == tr {
continue
if r != tr {
return false
}
return false
}

// First string is empty, so check if the second one is also empty.
return len(t) == 0
return true
}

// Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
Expand Down

0 comments on commit 32f452a

Please sign in to comment.