From bca616b5ddaed96d1b3354620594fcced5250549 Mon Sep 17 00:00:00 2001 From: David-Mao Date: Wed, 5 Jul 2023 19:04:11 -0400 Subject: [PATCH] slices: change implementation for Clone() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change the implementation of slices Clone. It's 28% faster on my laptop. As discussed in https://github.com/golang/go/issues/57433#issuecomment-1403961661, no extra issue is needed for this simple fix. goos: darwin goarch: arm64 pkg: github.com/David-Mao/Euclid/Go/utils │ old.txt │ new.txt │ │ sec/op │ sec/op vs base │ Clone-12 16.95n ± 1% 12.06n ± 2% -28.85% (p=0.000 n=10) --- src/slices/slices.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slices/slices.go b/src/slices/slices.go index afeed0afb522ce..9c87365071ddb2 100644 --- a/src/slices/slices.go +++ b/src/slices/slices.go @@ -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.