Skip to content

Commit

Permalink
slices: return quickly for Compact of one element
Browse files Browse the repository at this point in the history
Change-Id: I993c34b2cedc18da3500d3ddcbdeeb6bbc73d10f
GitHub-Last-Rev: 1620ea0
GitHub-Pull-Request: #46
Reviewed-on: https://go-review.googlesource.com/c/exp/+/448878
Auto-Submit: Keith Randall <[email protected]>
Reviewed-by: Keith Randall <[email protected]>
Reviewed-by: Keith Randall <[email protected]>
Run-TryBot: Keith Randall <[email protected]>
Reviewed-by: Ian Lance Taylor <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
  • Loading branch information
Asuan authored and gopherbot committed Nov 10, 2022
1 parent fc8884a commit d0897a7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
4 changes: 2 additions & 2 deletions slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ func Clone[S ~[]E, E any](s S) S {
// This is like the uniq command found on Unix.
// Compact modifies the contents of the slice s; it does not create a new slice.
func Compact[S ~[]E, E comparable](s S) S {
if len(s) == 0 {
if len(s) < 2 {
return s
}
i := 1
Expand All @@ -210,7 +210,7 @@ func Compact[S ~[]E, E comparable](s S) S {

// CompactFunc is like Compact but uses a comparison function.
func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S {
if len(s) == 0 {
if len(s) < 2 {
return s
}
i := 1
Expand Down
21 changes: 21 additions & 0 deletions slices/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -497,30 +497,37 @@ func TestClone(t *testing.T) {
}

var compactTests = []struct {
name string
s []int
want []int
}{
{
"nil",
nil,
nil,
},
{
"one",
[]int{1},
[]int{1},
},
{
"sorted",
[]int{1, 2, 3},
[]int{1, 2, 3},
},
{
"1 item",
[]int{1, 1, 2},
[]int{1, 2},
},
{
"unsorted",
[]int{1, 2, 1},
[]int{1, 2, 1},
},
{
"many",
[]int{1, 2, 2, 3, 3, 4},
[]int{1, 2, 3, 4},
},
Expand All @@ -535,6 +542,20 @@ func TestCompact(t *testing.T) {
}
}

func BenchmarkCompact(b *testing.B) {
for _, c := range compactTests {
b.Run(c.name, func(b *testing.B) {
ss := make([]int, 0, 64)
for k := 0; k < b.N; k++ {
ss = ss[:0]
ss = append(ss, c.s...)
_ = Compact(ss)
}
})
}

}

func TestCompactFunc(t *testing.T) {
for _, test := range compactTests {
copy := Clone(test.s)
Expand Down

0 comments on commit d0897a7

Please sign in to comment.