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

sort: sort.Slice more slower than sort.Sort #22504

Closed
ipfans opened this issue Oct 31, 2017 · 2 comments
Closed

sort: sort.Slice more slower than sort.Sort #22504

ipfans opened this issue Oct 31, 2017 · 2 comments

Comments

@ipfans
Copy link

ipfans commented Oct 31, 2017

What version of Go are you using (go version)?

1.9.2

Does this issue reproduce with the latest release?

YES

What operating system and processor architecture are you using (go env)?

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GORACE=""

What did you do?

// example from sort.Sort

func BenchmarkSort(b *testing.B) {
	var people = []Person{
		{"Bob", 31},
		{"John", 42},
		{"Michael", 17},
		{"Jenny", 26},
	}
	for i := 0; i < b.N; i++ {
		sort.Sort(ByAge(people))
	}
}

func BenchmarkSortSlice(b *testing.B) {
	var people = []Person{
		{"Bob", 31},
		{"John", 42},
		{"Michael", 17},
		{"Jenny", 26},
	}
	for i := 0; i < b.N; i++ {
		sort.Slice(people, func(i int, j int) bool {
			return people[i].Age < people[j].Age
		})
	}
}

What did you expect to see?

sort.Slice as fast as sort.Sort or a little slower than sort.Sort.

What did you see instead?

sort.Sort about 2.6x faster than sort.Slice.

$ go test -bench .
goos: darwin
goarch: amd64
BenchmarkSort-4         20000000                82.4 ns/op
BenchmarkSortSlice-4    10000000               211 ns/op
PASS
@davecheney
Copy link
Contributor

sort.Slice uses reflection to avoid the moderate amount of boilerplate required for sort.Sort.

I'm going to close this issue as it not directly actionable. It is not a bug in the sort package (we don't expect sort.Slice to be as fast as sort.Sort) and there are other general bugs about the performance of the reflect package.

@bradfitz
Copy link
Contributor

Sometimes sort.Slice is actually faster, depending on the type of elements being sorted. But sometimes sort.Sort is faster.

@golang golang locked and limited conversation to collaborators Oct 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants