Last active
August 13, 2026 16:09
-
-
Save alexedwards/36f3ec4965a2446f049911635c729098 to your computer and use it in GitHub Desktop.
JSON encoding benchmarks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 healthcheckHandlerMarshalWrite(w http.ResponseWriter, r *http.Request) { | |
| err := json.MarshalWrite(w, data) | |
| if err != nil { | |
| http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError) | |
| return | |
| } | |
| } | |
| func healthcheckHandlerMarshalEncode(w http.ResponseWriter, r *http.Request) { | |
| err := json.MarshalEncode(jsontext.NewEncoder(w), data) | |
| if err != nil { | |
| http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError) | |
| return | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "net/http" | |
| "net/http/httptest" | |
| "testing" | |
| ) | |
| func BenchmarkMarshal(b *testing.B) { | |
| r := httptest.NewRequest(http.MethodGet, "/", nil) | |
| w := httptest.NewRecorder() | |
| for b.Loop() { | |
| w.Body.Reset() | |
| healthcheckHandlerMarshal(w, r) | |
| } | |
| } | |
| func BenchmarkMarshalWrite(b *testing.B) { | |
| r := httptest.NewRequest(http.MethodGet, "/", nil) | |
| w := httptest.NewRecorder() | |
| for b.Loop() { | |
| w.Body.Reset() | |
| healthcheckHandlerMarshalWrite(w, r) | |
| } | |
| } | |
| func BenchmarkMarshalEncode(b *testing.B) { | |
| r := httptest.NewRequest(http.MethodGet, "/", nil) | |
| w := httptest.NewRecorder() | |
| for b.Loop() { | |
| w.Body.Reset() | |
| healthcheckHandlerMarshalEncode(w, r) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment