Created
November 10, 2020 10:20
-
-
Save alexedwards/809db1839a062c4f92a65f40359e18b7 to your computer and use it in GitHub Desktop.
JSON encoding benchmarks #2
This file contains 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" | |
"net/http" | |
) | |
func main() {} | |
func healthcheckHandlerMarshalIndent(w http.ResponseWriter, r *http.Request) { | |
data := map[string]string{ | |
"status": "available", | |
"environment": "development", | |
"version": "1.0.0", | |
} | |
js, err := json.MarshalIndent(data, "", "\t") | |
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) | |
} | |
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) | |
} |
This file contains 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 BenchmarkMarshalIndent(b *testing.B) { | |
w := httptest.NewRecorder() | |
r := new(http.Request) | |
for n := 0; n < b.N; n++ { | |
healthcheckHandlerMarshalIndent(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