From f8024de2ce5e0543e3c40e4532fc5af6fd9d0a31 Mon Sep 17 00:00:00 2001 From: Samuel Berthe Date: Sun, 6 Jul 2025 15:33:18 +0200 Subject: [PATCH] fix(chunk): Copy chunk in a new slice (#648) Prevents memory leak and free memory from initial collection. --- Makefile | 2 ++ slice.go | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index f97ded8..8badbda 100644 --- a/Makefile +++ b/Makefile @@ -25,6 +25,8 @@ tools: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest go get -t -u golang.org/x/tools/cmd/cover go install github.com/sonatype-nexus-community/nancy@latest + go install golang.org/x/perf/cmd/benchstat@latest + go install github.com/cespare/prettybench@latest go mod tidy lint: diff --git a/slice.go b/slice.go index 9c15a6c..0ee817f 100644 --- a/slice.go +++ b/slice.go @@ -221,7 +221,11 @@ func Chunk[T any, Slice ~[]T](collection Slice, size int) []Slice { if last > len(collection) { last = len(collection) } - result = append(result, collection[i*size:last:last]) + + // Copy chunk in a new slice, to prevent memory leak and free memory from initial collection. + newSlice := make(Slice, last-i*size) + copy(newSlice, collection[i*size:last]) + result = append(result, newSlice) } return result