Skip to content

Commit 7cd0b89

Browse files
feliixxdomodwyer
authored andcommitted
reduce memory allocation in bulk op (#56)
use memory pooling to reuse bulkActions and avoid some allocations
1 parent 663dfe5 commit 7cd0b89

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

bulk.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package mgo
33
import (
44
"bytes"
55
"sort"
6+
"sync"
67

78
"github.com/globalsign/mgo/bson"
89
)
@@ -118,6 +119,15 @@ func (e *BulkError) Cases() []BulkErrorCase {
118119
return e.ecases
119120
}
120121

122+
var actionPool = sync.Pool{
123+
New: func() interface{} {
124+
return &bulkAction{
125+
docs: make([]interface{}, 0),
126+
idxs: make([]int, 0),
127+
}
128+
},
129+
}
130+
121131
// Bulk returns a value to prepare the execution of a bulk operation.
122132
func (c *Collection) Bulk() *Bulk {
123133
return &Bulk{c: c, ordered: true}
@@ -145,7 +155,9 @@ func (b *Bulk) action(op bulkOp, opcount int) *bulkAction {
145155
}
146156
}
147157
if action == nil {
148-
b.actions = append(b.actions, bulkAction{op: op})
158+
a := actionPool.Get().(*bulkAction)
159+
a.op = op
160+
b.actions = append(b.actions, *a)
149161
action = &b.actions[len(b.actions)-1]
150162
}
151163
for i := 0; i < opcount; i++ {
@@ -288,6 +300,9 @@ func (b *Bulk) Run() (*BulkResult, error) {
288300
default:
289301
panic("unknown bulk operation")
290302
}
303+
action.idxs = action.idxs[0:0]
304+
action.docs = action.docs[0:0]
305+
actionPool.Put(action)
291306
if !ok {
292307
failed = true
293308
if b.ordered {

0 commit comments

Comments
 (0)