Remove allocations while logging an Array of Objects. (#38)

This commit is contained in:
Giovanni Bajo 2018-02-13 20:18:01 +01:00 committed by Olivier Poitrey
parent a717e7cbed
commit 9ee98f91c4
3 changed files with 21 additions and 3 deletions

View File

@ -48,6 +48,7 @@ func (a *Array) Object(obj LogObjectMarshaler) *Array {
obj.MarshalZerologObject(e)
e.buf = append(e.buf, '}')
a.buf = append(a.buf, e.buf...)
eventPool.Put(e)
return a
}

View File

@ -96,6 +96,22 @@ func (o obj) MarshalZerologObject(e *Event) {
Int("priv", o.priv)
}
func BenchmarkLogArrayObject(b *testing.B) {
obj1 := obj{"a", "b", 2}
obj2 := obj{"c", "d", 3}
obj3 := obj{"e", "f", 4}
logger := New(ioutil.Discard)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
arr := Arr()
arr.Object(&obj1)
arr.Object(&obj2)
arr.Object(&obj3)
logger.Info().Array("objects", arr).Msg("test")
}
}
func BenchmarkLogFieldType(b *testing.B) {
bools := []bool{true, false, true, false, true, false, true, false, true, false}
ints := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

View File

@ -2,7 +2,6 @@ package zerolog
import (
"fmt"
"io/ioutil"
"os"
"runtime"
"strconv"
@ -61,7 +60,9 @@ func (e *Event) write() (err error) {
return nil
}
e.buf = append(e.buf, '}', '\n')
_, err = e.w.WriteLevel(e.level, e.buf)
if e.w != nil {
_, err = e.w.WriteLevel(e.level, e.buf)
}
eventPool.Put(e)
return
}
@ -142,7 +143,7 @@ func (e *Event) Dict(key string, dict *Event) *Event {
// Call usual field methods like Str, Int etc to add fields to this
// event and give it as argument the *Event.Dict method.
func Dict() *Event {
return newEvent(levelWriterAdapter{ioutil.Discard}, 0, true)
return newEvent(nil, 0, true)
}
// Array adds the field key with an array to the event context.