Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmp: optimize Compare #63360

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/cmp/bench_test.go
Original file line number Diff line number Diff line change
@@ -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)])
}
}
20 changes: 11 additions & 9 deletions src/cmp/cmp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down