Browse Source

mvcc: preallocate bytes buffer for saveIndex

Gyu-Ho Lee 9 năm trước cách đây
mục cha
commit
77775e8e92
2 tập tin đã thay đổi với 17 bổ sung4 xóa
  1. 6 2
      mvcc/kvstore.go
  2. 11 2
      mvcc/kvstore_bench_test.go

+ 6 - 2
mvcc/kvstore.go

@@ -75,6 +75,10 @@ type store struct {
 	tx    backend.BatchTx
 	txnID int64 // tracks the current txnID to verify txn operations
 
+	// bytesBuf8 is a byte slice of length 8
+	// to avoid a repetitive allocation in saveIndex.
+	bytesBuf8 []byte
+
 	changes   []mvccpb.KeyValue
 	fifoSched schedule.Scheduler
 
@@ -94,6 +98,7 @@ func NewStore(b backend.Backend, le lease.Lessor, ig ConsistentIndexGetter) *sto
 		currentRev:     revision{main: 1},
 		compactMainRev: -1,
 
+		bytesBuf8: make([]byte, 8, 8),
 		fifoSched: schedule.NewFIFOScheduler(),
 
 		stopc: make(chan struct{}),
@@ -595,8 +600,7 @@ func (s *store) saveIndex() {
 		return
 	}
 	tx := s.tx
-	// TODO: avoid this unnecessary allocation
-	bs := make([]byte, 8)
+	bs := s.bytesBuf8
 	binary.BigEndian.PutUint64(bs, s.ig.ConsistentIndex())
 	// put the index into the underlying backend
 	// tx has been locked in TxnBegin, so there is no need to lock it again

+ 11 - 2
mvcc/kvstore_bench_test.go

@@ -16,15 +16,23 @@ package mvcc
 
 import (
 	"log"
+	"sync/atomic"
 	"testing"
 
 	"github.com/coreos/etcd/lease"
 	"github.com/coreos/etcd/mvcc/backend"
 )
 
+type fakeConsistentIndex uint64
+
+func (i *fakeConsistentIndex) ConsistentIndex() uint64 {
+	return atomic.LoadUint64((*uint64)(i))
+}
+
 func BenchmarkStorePut(b *testing.B) {
+	var i fakeConsistentIndex
 	be, tmpPath := backend.NewDefaultTmpBackend()
-	s := NewStore(be, &lease.FakeLessor{}, nil)
+	s := NewStore(be, &lease.FakeLessor{}, &i)
 	defer cleanup(s, be, tmpPath)
 
 	// arbitrary number of bytes
@@ -42,8 +50,9 @@ func BenchmarkStorePut(b *testing.B) {
 // with transaction begin and end, where transaction involves
 // some synchronization operations, such as mutex locking.
 func BenchmarkStoreTxnPut(b *testing.B) {
+	var i fakeConsistentIndex
 	be, tmpPath := backend.NewDefaultTmpBackend()
-	s := NewStore(be, &lease.FakeLessor{}, nil)
+	s := NewStore(be, &lease.FakeLessor{}, &i)
 	defer cleanup(s, be, tmpPath)
 
 	// arbitrary number of bytes