From 4f927c3527fcca94c0c49aec59cd558c3384cf89 Mon Sep 17 00:00:00 2001 From: Sebastien Binet Date: Mon, 4 Apr 2022 17:23:51 +0200 Subject: [PATCH] sliceop: improve performances of Take MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit name old time/op new time/op delta Take/Len=2-8 2.95ns ± 2% 2.96ns ± 2% ~ (p=0.952 n=20+20) Take/Len=4-8 3.43ns ± 1% 3.67ns ± 1% +6.96% (p=0.000 n=20+19) Take/Len=8-8 3.92ns ± 2% 4.17ns ± 1% +6.31% (p=0.000 n=19+20) Take/Len=128-8 36.4ns ± 2% 35.6ns ± 2% -2.21% (p=0.000 n=20+20) Take/Len=1024-8 278ns ± 5% 271ns ± 2% -2.29% (p=0.001 n=17+19) Take/Len=1048576-8 1.27ms ± 2% 0.67ms ± 6% -46.97% (p=0.000 n=19+20) name old alloc/op new alloc/op delta Take/Len=2-8 0.00B 0.00B ~ (all equal) Take/Len=4-8 0.00B 0.00B ~ (all equal) Take/Len=8-8 0.00B 0.00B ~ (all equal) Take/Len=128-8 0.00B 0.00B ~ (all equal) Take/Len=1024-8 0.00B 0.00B ~ (all equal) Take/Len=1048576-8 0.00B 0.00B ~ (all equal) name old allocs/op new allocs/op delta Take/Len=2-8 0.00 0.00 ~ (all equal) Take/Len=4-8 0.00 0.00 ~ (all equal) Take/Len=8-8 0.00 0.00 ~ (all equal) Take/Len=128-8 0.00 0.00 ~ (all equal) Take/Len=1024-8 0.00 0.00 ~ (all equal) Take/Len=1048576-8 0.00 0.00 ~ (all equal) --- sliceop/sliceop.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sliceop/sliceop.go b/sliceop/sliceop.go index 4a73530fe..4d1d309d7 100644 --- a/sliceop/sliceop.go +++ b/sliceop/sliceop.go @@ -101,8 +101,11 @@ func Take[T any](dst, src []T, indices []int) []T { } dst[0] = src[indices[0]] - for i := 1; i < len(indices); i++ { - v0 := indices[i-1] + var ( + v0 = indices[0] + nn = len(indices) + ) + for i := 1; i < nn; i++ { v1 := indices[i] switch { case v0 < v1: @@ -112,8 +115,10 @@ func Take[T any](dst, src []T, indices []int) []T { case v0 > v1: panic(errSortedIndices) } - dst[i] = src[v1] + dst[i-1] = src[v0] + v0 = v1 } + dst[nn-1] = src[v0] return dst }