diff --git a/src/cmp/bench_test.go b/src/cmp/bench_test.go new file mode 100644 index 00000000000000..d3541a672a3d42 --- /dev/null +++ b/src/cmp/bench_test.go @@ -0,0 +1,57 @@ +package cmp_test + +import ( + "cmp" + "math" + "testing" +) + +var sum int + +func BenchmarkCompare_int(b *testing.B) { + lst := [...]int{ + 0xfa3, 0x7fe, 0x03c, 0xcb9, + 0x4ce, 0x4fb, 0x7d5, 0x38f, + 0x73b, 0x322, 0x85c, 0xf4d, + 0xbbc, 0x032, 0x059, 0xb93, + } + for n := 0; n < b.N; n++ { + sum += cmp.Compare(lst[n%len(lst)], lst[(2*n)%len(lst)]) + } +} + +func BenchmarkCompare_float64(b *testing.B) { + lst := [...]float64{ + 0.35573281, 0.77552566, 0.19006500, 0.66436280, + 0.02769279, 0.97572397, 0.40945068, 0.26422857, + 0.10985792, 0.35659522, 0.82752613, 0.18875522, + 0.16410543, 0.03578153, 0.51636871, math.NaN(), + } + for n := 0; n < b.N; n++ { + sum += cmp.Compare(lst[n%len(lst)], lst[(2*n)%len(lst)]) + } +} + +func BenchmarkCompare_strings(b *testing.B) { + lst := [...]string{ + "time", + "person", + "year", + "way", + "day", + "thing", + "man", + "world", + "life", + "hand", + "part", + "child", + "eye", + "woman", + "place", + "work", + } + for n := 0; n < b.N; n++ { + sum += cmp.Compare(lst[n%len(lst)], lst[(2*n)%len(lst)]) + } +} diff --git a/src/cmp/cmp.go b/src/cmp/cmp.go index 4d1af6a98c4e46..fc69b8b2294a73 100644 --- a/src/cmp/cmp.go +++ b/src/cmp/cmp.go @@ -38,15 +38,17 @@ func Less[T Ordered](x, y T) bool { // For floating-point types, a NaN is considered less than any non-NaN, // a NaN is considered equal to a NaN, and -0.0 is equal to 0.0. func Compare[T Ordered](x, y T) int { - xNaN := isNaN(x) - yNaN := isNaN(y) - if xNaN && yNaN { - return 0 - } - if xNaN || x < y { - return -1 - } - if yNaN || x > y { + if x != y { + if isNaN(x) { + if isNaN(y) { + return 0 + } + return -1 + } + // If isNaN(y), x < y is false. + if x < y { + return -1 + } return +1 } return 0