From 2f2827310efcb0485124ed9384bb49f88ea81596 Mon Sep 17 00:00:00 2001 From: Yan Mikhaylov Andreevich Date: Fri, 14 Jun 2024 17:54:42 +0300 Subject: [PATCH] [master] ToSlicePtr: improve speed --- slice_benchmark_test.go | 7 +++++++ type_manipulation.go | 9 ++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/slice_benchmark_test.go b/slice_benchmark_test.go index 38911c08..6b085116 100644 --- a/slice_benchmark_test.go +++ b/slice_benchmark_test.go @@ -171,3 +171,10 @@ func BenchmarkReplace(b *testing.B) { }) } } + +func BenchmarkToSlicePtr(b *testing.B) { + preallocated := make([]int, 100000) + for i := 0; i < b.N; i++ { + _ = ToSlicePtr(preallocated) + } +} diff --git a/type_manipulation.go b/type_manipulation.go index ec787189..83fad2e2 100644 --- a/type_manipulation.go +++ b/type_manipulation.go @@ -45,9 +45,12 @@ func FromPtrOr[T any](x *T, fallback T) T { // ToSlicePtr returns a slice of pointer copy of value. func ToSlicePtr[T any](collection []T) []*T { - return Map(collection, func(x T, _ int) *T { - return &x - }) + result := make([]*T, len(collection)) + + for i := range collection { + result[i] = &collection[i] + } + return result } // ToAnySlice returns a slice with all elements mapped to `any` type