From 6916bd9824a549ef0620795158dcb7b7ce26e6ad Mon Sep 17 00:00:00 2001 From: 1911860538 Date: Sat, 15 Feb 2025 16:25:17 +0800 Subject: [PATCH 1/2] perf: optimize MemoryStorage.Compact method by improving memory allocation Signed-off-by: huangzw --- storage.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/storage.go b/storage.go index f616c315..8d8a0c85 100644 --- a/storage.go +++ b/storage.go @@ -263,10 +263,9 @@ func (ms *MemoryStorage) Compact(compactIndex uint64) error { // NB: allocate a new slice instead of reusing the old ms.ents. Entries in // ms.ents are immutable, and can be referenced from outside MemoryStorage // through slices returned by ms.Entries(). - ents := make([]pb.Entry, 1, uint64(len(ms.ents))-i) - ents[0].Index = ms.ents[i].Index - ents[0].Term = ms.ents[i].Term - ents = append(ents, ms.ents[i+1:]...) + remainingCount := len(ms.ents) - int(i) + ents := make([]pb.Entry, remainingCount) + copy(ents, ms.ents[i:]) ms.ents = ents return nil } From 04f8874aa9231c97cec223f38482602b0bf398d5 Mon Sep 17 00:00:00 2001 From: 1911860538 Date: Sat, 15 Feb 2025 16:39:12 +0800 Subject: [PATCH 2/2] fix: resolve uint64 type mismatch in remaining entries calculation in Compact method Signed-off-by: huangzw --- storage.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/storage.go b/storage.go index 8d8a0c85..516f7cce 100644 --- a/storage.go +++ b/storage.go @@ -263,7 +263,7 @@ func (ms *MemoryStorage) Compact(compactIndex uint64) error { // NB: allocate a new slice instead of reusing the old ms.ents. Entries in // ms.ents are immutable, and can be referenced from outside MemoryStorage // through slices returned by ms.Entries(). - remainingCount := len(ms.ents) - int(i) + remainingCount := uint64(len(ms.ents)) - i ents := make([]pb.Entry, remainingCount) copy(ents, ms.ents[i:]) ms.ents = ents