Home > Backend Development > Golang > 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?

王林
Release: 2024-02-13 21:03:08
forward
624 people have browsed it

`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) { ... }
Copy after login

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))
Copy after login

This will output (try it on Go Playground):

ſ s
2 1 true
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template