[TextFormatter] Speed up. Fprintf is changed to buffer.Write*

As Fprintf is slower than buffer.WriteString, it's replaced
to faster call.

Signed-off-by: Anton Tiurin <noxiouz@yandex.ru>
This commit is contained in:
Anton Tiurin 2015-06-27 17:09:22 +03:00
parent 93a1736895
commit e35e0e00b8
2 changed files with 26 additions and 9 deletions

View File

@ -1,6 +1,7 @@
package logrus package logrus
import ( import (
"fmt"
"testing" "testing"
"time" "time"
) )
@ -45,6 +46,15 @@ var largeFields = Fields{
"entries": "yeah", "entries": "yeah",
} }
var errorFields = Fields{
"foo": fmt.Errorf("bar"),
"baz": fmt.Errorf("qux"),
}
func BenchmarkErrorTextFormatter(b *testing.B) {
doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields)
}
func BenchmarkSmallTextFormatter(b *testing.B) { func BenchmarkSmallTextFormatter(b *testing.B) {
doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields)
} }

View File

@ -131,21 +131,28 @@ func needsQuoting(text string) bool {
return true return true
} }
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) { func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
switch value.(type) {
b.WriteString(key)
b.WriteByte('=')
switch value := value.(type) {
case string: case string:
if needsQuoting(value.(string)) { if needsQuoting(value) {
fmt.Fprintf(b, "%v=%s ", key, value) b.WriteString(value)
} else { } else {
fmt.Fprintf(b, "%v=%q ", key, value) fmt.Fprintf(b, "%q", value)
} }
case error: case error:
if needsQuoting(value.(error).Error()) { errmsg := value.Error()
fmt.Fprintf(b, "%v=%s ", key, value) if needsQuoting(errmsg) {
b.WriteString(errmsg)
} else { } else {
fmt.Fprintf(b, "%v=%q ", key, value) fmt.Fprintf(b, "%q", value)
} }
default: default:
fmt.Fprintf(b, "%v=%v ", key, value) fmt.Fprint(b, value)
} }
b.WriteByte(' ')
} }