From 208b8a349c24bcd9300740d3c8815acd440864f0 Mon Sep 17 00:00:00 2001 From: Nathan VanBenschoten Date: Fri, 26 Apr 2019 00:10:45 -0400 Subject: [PATCH] raft: Avoid allocation when boxing slice in maybeCommit By boxing a heap-allocated slice header instead of the slice header on the stack, we can avoid an allocation when passing through the sort.Interface interface. This was responsible for 26.61% of total allocations in an experiment with https://github.com/nvanbenschoten/raft-toy. --- raft/raft.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/raft/raft.go b/raft/raft.go index 61ad12ccb..0abf1cdeb 100644 --- a/raft/raft.go +++ b/raft/raft.go @@ -607,14 +607,14 @@ func (r *raft) maybeCommit() bool { if cap(r.matchBuf) < len(r.prs) { r.matchBuf = make(uint64Slice, len(r.prs)) } - mis := r.matchBuf[:len(r.prs)] + r.matchBuf = r.matchBuf[:len(r.prs)] idx := 0 for _, p := range r.prs { - mis[idx] = p.Match + r.matchBuf[idx] = p.Match idx++ } - sort.Sort(mis) - mci := mis[len(mis)-r.quorum()] + sort.Sort(&r.matchBuf) + mci := r.matchBuf[len(r.matchBuf)-r.quorum()] return r.raftLog.maybeCommit(mci, r.Term) }