Skip to content

Commit

Permalink
c.String() performance improvements
Browse files Browse the repository at this point in the history
```
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%
```
  • Loading branch information
manucorporat committed Jun 4, 2015
1 parent 7186200 commit 56683d3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
6 changes: 2 additions & 4 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 8 additions & 4 deletions render/text.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 56683d3

Please sign in to comment.