From 56683d33b1d7cb08b6fa5c0fbc81a595bec7dc65 Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Thu, 4 Jun 2015 12:53:42 +0200 Subject: [PATCH] c.String() performance improvements ``` benchmark old ns/op new ns/op delta BenchmarkOneRouteString 448 310 -30.80% benchmark old allocs new allocs delta BenchmarkOneRouteString 1 0 -100.00% benchmark old bytes new bytes delta BenchmarkOneRouteString 48 0 -100.00% ``` --- context.go | 6 ++---- render/text.go | 12 ++++++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/context.go b/context.go index b54db50..1ab182c 100644 --- a/context.go +++ b/context.go @@ -320,10 +320,8 @@ func (c *Context) XML(code int, obj interface{}) { // Writes the given string into the response body. func (c *Context) String(code int, format string, values ...interface{}) { - c.Render(code, render.String{ - Format: format, - Data: values}, - ) + c.writermem.WriteHeader(code) + render.WriteString(c.Writer, format, values) } // Returns a HTTP redirect to the specific location. diff --git a/render/text.go b/render/text.go index 97d60bb..22a8c99 100644 --- a/render/text.go +++ b/render/text.go @@ -18,14 +18,18 @@ type String struct { var plainContentType = []string{"text/plain; charset=utf-8"} func (r String) Render(w http.ResponseWriter) error { + WriteString(w, r.Format, r.Data) + return nil +} + +func WriteString(w http.ResponseWriter, format string, data []interface{}) { header := w.Header() if _, exist := header["Content-Type"]; !exist { header["Content-Type"] = plainContentType } - if len(r.Data) > 0 { - fmt.Fprintf(w, r.Format, r.Data...) + if len(data) > 0 { + fmt.Fprintf(w, format, data...) } else { - io.WriteString(w, r.Format) + io.WriteString(w, format) } - return nil }