From b5593de80692416a5b32130488bc94188ac75e8d Mon Sep 17 00:00:00 2001 From: Nathan VanBenschoten Date: Fri, 26 Apr 2019 14:57:51 -0400 Subject: [PATCH] raft: Avoid multiple allocs when merging stable and unstable log Appending to an empty slice twice could (and often did) result in multiple allocations. This was wasteful. We can avoid this by performing a single allocation with the correct size and copying into it. --- raft/log.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/raft/log.go b/raft/log.go index 03f83e61c42..77eedfccbad 100644 --- a/raft/log.go +++ b/raft/log.go @@ -332,8 +332,10 @@ func (l *raftLog) slice(lo, hi, maxSize uint64) ([]pb.Entry, error) { if hi > l.unstable.offset { unstable := l.unstable.slice(max(lo, l.unstable.offset), hi) if len(ents) > 0 { - ents = append([]pb.Entry{}, ents...) - ents = append(ents, unstable...) + combined := make([]pb.Entry, len(ents)+len(unstable)) + n := copy(combined, ents) + copy(combined[n:], unstable) + ents = combined } else { ents = unstable }