Skip to content

Commit

Permalink
[master] ToSlicePtr: improve speed
Browse files Browse the repository at this point in the history
  • Loading branch information
Yan Mikhaylov Andreevich committed Jun 14, 2024
1 parent 71d8341 commit 2f28273
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
7 changes: 7 additions & 0 deletions slice_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
9 changes: 6 additions & 3 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 2f28273

Please sign in to comment.