func Compare(a, b string) int {
// NOTE(rsc): This function does NOT call the runtime cmpstring function,
// because we do not want to provide any performance justification for
// using strings.Compare. Basically no one should use strings.Compare.
// As the comment above says, it is here only for symmetry with package bytes.
// If performance is important, the compiler should be changed to recognize
// the pattern so that all code doing three-way comparisons, not just code
// using strings.Compare, can benefit.
if a == b {
return 0
}
if a < b {
return -1
}
return +1
}
func Compare(a, b []byte) int {
return bytealg.Compare(a, b)
}
strings.Compare
implementation is comparatively inefficient. Specifically, it is less efficient when the two string operands are not equal but their lengths are equal.
strings.Compare
uses 2x CPU time of bytes.Compare
when comparing unequal same-length byte sequences (we view both strings and byte slices as byte sequences here).
strings.Compare
implementation is some interesting. The comment suggests that we should not use strings.Compare
in Go at all, but no alternative efficient ways are available now yet (ironically, this function is used in Go toolchain code and recommended by a standard library function). It mentions that the compiler should make special optimizations to automatically convert the code using comparison operators into internal optimized three-way comparisons if possible. However, such compiler optimizations have never been made, and there are no plans to make such optimizations yet as far as I know. Personally, I doubt such optimizations are feasible to be made for every use case. So I think the strings.Compare
should be implemented efficiently, to avoid breaking user expectations.
strings.Compare
function got optimizted in Go 1.23.
The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.
If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.