Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Last active August 13, 2026 17:19
Show Gist options
  • Select an option

  • Save alexedwards/18559aaf822bc37d985097d3833d7f8b to your computer and use it in GitHub Desktop.

Select an option

Save alexedwards/18559aaf822bc37d985097d3833d7f8b to your computer and use it in GitHub Desktop.
JSON decoding benchmarks
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"io"
"net/http"
)
var input struct {
Title string `json:"title"`
Year int `json:"year"`
Genres []string `json:"genres"`
}
func main() {}
func createMovieHandlerUnmarshal(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
return
}
err = json.Unmarshal(body, &input)
if err != nil {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
return
}
}
func createMovieHandlerUnmarshalRead(w http.ResponseWriter, r *http.Request) {
err := json.UnmarshalRead(r.Body, &input)
if err != nil {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
return
}
}
func createMovieHandlerUnmarshalDecode(w http.ResponseWriter, r *http.Request) {
dec := jsontext.NewDecoder(r.Body)
err := json.UnmarshalDecode(dec, &input)
if err != nil {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
return
}
}
package main
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const body = `{"title":"Moana","year":2016,"genres":["animation","adventure"]}`
func BenchmarkUnmarshal(b *testing.B) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
for b.Loop() {
r.Body = io.NopCloser(strings.NewReader(body))
w.Body.Reset()
createMovieHandlerUnmarshal(w, r)
}
}
func BenchmarkUnmarshalRead(b *testing.B) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
for b.Loop() {
r.Body = io.NopCloser(strings.NewReader(body))
w.Body.Reset()
createMovieHandlerUnmarshalRead(w, r)
}
}
func BenchmarkUnmarshalDecode(b *testing.B) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
for b.Loop() {
r.Body = io.NopCloser(strings.NewReader(body))
w.Body.Reset()
createMovieHandlerUnmarshalDecode(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment