From 3ce85fffd029404687eb1c8ca80d19d3a20dd911 Mon Sep 17 00:00:00 2001
From: Wolfgang Welz <welzwo@gmail.com>
Date: Thu, 13 Jun 2019 15:02:02 +0200
Subject: [PATCH] Reduce number of allocations when iterating through the db

---
 packages/database/database.go | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/packages/database/database.go b/packages/database/database.go
index 5ac305d6..948bf19f 100644
--- a/packages/database/database.go
+++ b/packages/database/database.go
@@ -120,23 +120,26 @@ func (this *databaseImpl) Delete(key []byte) error {
 	return err
 }
 
-func (this *databaseImpl) ForEach(consumer func(key []byte, value []byte)) error {
+func (this *databaseImpl) ForEach(consumer func([]byte, []byte)) error {
 	err := this.db.View(func(txn *badger.Txn) error {
 		// create an iterator the default options
 		it := txn.NewIterator(badger.DefaultIteratorOptions)
 		defer it.Close()
 
+		// avoid allocations by reusing the value buffer
+		var value []byte
+
 		// loop through every key-value-pair and call the function
 		for it.Rewind(); it.Valid(); it.Next() {
 			item := it.Item()
 
-			key := item.Key()
-			value, err := item.ValueCopy(nil)
+			var err error
+			value, err = item.ValueCopy(value)
 			if err != nil {
 				return err
 			}
 
-			consumer(key, value)
+			consumer(item.Key(), value)
 		}
 		return nil
 	})
-- 
GitLab