Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Last active February 19, 2024 07:16
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexedwards/8f11d0dc57fc119cbc791def783d8492 to your computer and use it in GitHub Desktop.
Save alexedwards/8f11d0dc57fc119cbc791def783d8492 to your computer and use it in GitHub Desktop.
JSON encoding benchmarks
package main
import (
"encoding/json"
"net/http"
)
func main() {}
func healthcheckHandlerEncoder(w http.ResponseWriter, r *http.Request) {
data := map[string]string{
"status": "available",
"environment": "development",
"version": "1.0.0",
}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(data)
if err != nil {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
}
}
func healthcheckHandlerMarshal(w http.ResponseWriter, r *http.Request) {
data := map[string]string{
"status": "available",
"environment": "development",
"version": "1.0.0",
}
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
}
js = append(js, '\n')
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func BenchmarkEncoder(b *testing.B) {
w := httptest.NewRecorder()
r := new(http.Request)
for n := 0; n < b.N; n++ {
healthcheckHandlerEncoder(w, r)
}
}
func BenchmarkMarshal(b *testing.B) {
w := httptest.NewRecorder()
r := new(http.Request)
for n := 0; n < b.N; n++ {
healthcheckHandlerMarshal(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment