Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created November 15, 2020 10:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexedwards/d3d44ef77efb91a6e16048f60e72c57d to your computer and use it in GitHub Desktop.
Save alexedwards/d3d44ef77efb91a6e16048f60e72c57d to your computer and use it in GitHub Desktop.
JSON decoding benchmarks
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
)
func createMovieHandlerUnmarshal(w http.ResponseWriter, r *http.Request) {
var input struct {
Title string `json:"title"`
Year int32 `json:"year"`
Runtime int32 `json:"runtime"`
Genres []string `json:"genres"`
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = json.Unmarshal(body, &input)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
func createMovieHandlerDecoder(w http.ResponseWriter, r *http.Request) {
var input struct {
Title string `json:"title"`
Year int32 `json:"year"`
Runtime int32 `json:"runtime"`
Genres []string `json:"genres"`
}
err := json.NewDecoder(r.Body).Decode(&input)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const body = `{"title":"Moana","year":2016,"runtime":107, "genres":["animation","adventure"]}`
func BenchmarkUnmarshal(b *testing.B) {
w := httptest.NewRecorder()
for n := 0; n < b.N; n++ {
r, err := http.NewRequest(http.MethodPost, "", strings.NewReader(body))
if err != nil {
b.Fatal(err)
}
createMovieHandlerUnmarshal(w, r)
}
}
func BenchmarkDecoder(b *testing.B) {
w := httptest.NewRecorder()
for n := 0; n < b.N; n++ {
r, err := http.NewRequest(http.MethodPost, "", strings.NewReader(body))
if err != nil {
b.Fatal(err)
}
createMovieHandlerDecoder(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment