Skip to content

Commit

Permalink
reduce memory allocation in bulk op (#56)
Browse files Browse the repository at this point in the history
use memory pooling to reuse bulkActions and
  avoid some allocations
  • Loading branch information
feliixx authored and domodwyer committed Nov 3, 2017
1 parent 663dfe5 commit 7cd0b89
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion bulk.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mgo
import (
"bytes"
"sort"
"sync"

"github.com/globalsign/mgo/bson"
)
Expand Down Expand Up @@ -118,6 +119,15 @@ func (e *BulkError) Cases() []BulkErrorCase {
return e.ecases
}

var actionPool = sync.Pool{
New: func() interface{} {
return &bulkAction{
docs: make([]interface{}, 0),
idxs: make([]int, 0),
}
},
}

// Bulk returns a value to prepare the execution of a bulk operation.
func (c *Collection) Bulk() *Bulk {
return &Bulk{c: c, ordered: true}
Expand Down Expand Up @@ -145,7 +155,9 @@ func (b *Bulk) action(op bulkOp, opcount int) *bulkAction {
}
}
if action == nil {
b.actions = append(b.actions, bulkAction{op: op})
a := actionPool.Get().(*bulkAction)
a.op = op
b.actions = append(b.actions, *a)
action = &b.actions[len(b.actions)-1]
}
for i := 0; i < opcount; i++ {
Expand Down Expand Up @@ -288,6 +300,9 @@ func (b *Bulk) Run() (*BulkResult, error) {
default:
panic("unknown bulk operation")
}
action.idxs = action.idxs[0:0]
action.docs = action.docs[0:0]
actionPool.Put(action)
if !ok {
failed = true
if b.ordered {
Expand Down

0 comments on commit 7cd0b89

Please sign in to comment.