Home  >  Article  >  Backend Development  >  Is there a reason why `strings.EqualFold` doesn't do a length comparison first?

Is there a reason why `strings.EqualFold` doesn't do a length comparison first?

王林
王林forward
2024-02-13 21:03:08507browse

`strings.EqualFold` 不首先进行长度比较是否有原因?

php Editor Apple, today we will discuss the reason why the `strings.EqualFold` function does not first perform a length comparison when comparing whether strings are equal. In string comparison, we often use the `strings.EqualFold` function to ignore case for comparison. However, some may wonder why this function doesn't perform a length comparison first? In the following article, we will answer this question and discuss the rationale of this design. Let’s take a look!

Question content

A common practice for comparing case-insensitive strings is to first explicitly check the length:

if len(a) == len(b) && strings.EqualFold(a, b) { ... }

This seems to be a workaround, as the current implementation only performs a length check when either of the two input strings is exhausted.

Is there a reason, performance or otherwise, not to do a length check first?

Solution

The short answer is because in Go 2 strings can have different lengths but still be equal under simple Unicode case folding (so doing a length comparison first does not Determine case fold equality).

The longer answer is: Go stores strings in memory as UTF-8 bytes, and the built-in len() function reports UTF -8 Number of bytes to encode. UTF-8 is a variable-length character encoding: it may use a different number of bytes for a single unicode code point, so matching case-folding code points may use a different number of bytes in UTF-8.

Look at an example to prove this:

s1, s2 := "\u017F", "\u0073"
fmt.Println(s1, s2)

fmt.Println(len(s1), len(s2), strings.EqualFold(s1, s2))

This will output (try it on Go Playground):

ſ s
2 1 true

The above is the detailed content of Is there a reason why `strings.EqualFold` doesn't do a length comparison first?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete