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

slices: make Clone preallocate and copy instead of solely invoking append #61186

Closed
wants to merge 1 commit 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
4 changes: 3 additions & 1 deletion src/slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,9 @@ func Clone[S ~[]E, E any](s S) S {
if s == nil {
return nil
}
return append(S([]E{}), s...)
t := make([]E, len(s))
copy(t, s)
return t
}

// Compact replaces consecutive runs of equal elements with a single copy.
Expand Down
56 changes: 56 additions & 0 deletions src/slices/slices_benchmark_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package slices

import (
"testing"
)

var sink any = nil

func BenchmarkIntClone_10B(b *testing.B) {
benchmarkClone[int](b, 10)
}

func BenchmarkIntClone_1Kb(b *testing.B) {
benchmarkClone[int](b, 1<<10)
}

func BenchmarkIntClone_10Kb(b *testing.B) {
benchmarkClone[int](b, 10<<10)
}

func BenchmarkIntClone_1Mb(b *testing.B) {
benchmarkClone[int](b, 1<<20)
}

func BenchmarkIntClone_10Mb(b *testing.B) {
benchmarkClone[int](b, 10<<20)
}

func BenchmarkByteClone_10B(b *testing.B) {
benchmarkClone[byte](b, 10)
}

func BenchmarkByteClone_10Kb(b *testing.B) {
benchmarkClone[byte](b, 10<<10)
}

func benchmarkClone[T int | byte](b *testing.B, n int) {
s1 := make([]T, n)
for i := 0; i < n/2; i++ {
s1[i] = T(i)
s1[n-i-1] = T(i * 2)
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
sink = Clone(s1)
}
if sink == nil {
b.Fatal("Benchmark did not run!")
}
sink = nil
}