Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created August 7, 2026 16:29
Show Gist options
  • Select an option

  • Save alexedwards/5fa7ae79eefb80e993ed5d64fe21c93c to your computer and use it in GitHub Desktop.

Select an option

Save alexedwards/5fa7ae79eefb80e993ed5d64fe21c93c to your computer and use it in GitHub Desktop.
JSON encoding benchmarks
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"net/http"
)
var data = map[string]string{
"status": "available",
"environment": "development",
"version": "1.0.0",
}
func main() {}
func healthcheckHandlerMarshal(w http.ResponseWriter, r *http.Request) {
js, err := json.Marshal(data)
if err != nil {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
return
}
w.Write(js)
}
func healthcheckHandlerMarshalMultiline(w http.ResponseWriter, r *http.Request) {
js, err := json.Marshal(data, jsontext.Multiline(true))
if err != nil {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
return
}
w.Write(js)
}
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func BenchmarkMarshal(b *testing.B) {
w := httptest.NewRecorder()
r := new(http.Request)
for b.Loop() {
healthcheckHandlerMarshal(w, r)
}
}
func BenchmarkMarshalMultiline(b *testing.B) {
w := httptest.NewRecorder()
r := new(http.Request)
for b.Loop() {
healthcheckHandlerMarshalMultiline(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment