Created
November 15, 2020 10:38
-
-
Save alexedwards/d3d44ef77efb91a6e16048f60e72c57d to your computer and use it in GitHub Desktop.
JSON decoding benchmarks
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" | |
"io/ioutil" | |
"net/http" | |
) | |
func createMovieHandlerUnmarshal(w http.ResponseWriter, r *http.Request) { | |
var input struct { | |
Title string `json:"title"` | |
Year int32 `json:"year"` | |
Runtime int32 `json:"runtime"` | |
Genres []string `json:"genres"` | |
} | |
body, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
err = json.Unmarshal(body, &input) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
} | |
func createMovieHandlerDecoder(w http.ResponseWriter, r *http.Request) { | |
var input struct { | |
Title string `json:"title"` | |
Year int32 `json:"year"` | |
Runtime int32 `json:"runtime"` | |
Genres []string `json:"genres"` | |
} | |
err := json.NewDecoder(r.Body).Decode(&input) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
} |
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" | |
"strings" | |
"testing" | |
) | |
const body = `{"title":"Moana","year":2016,"runtime":107, "genres":["animation","adventure"]}` | |
func BenchmarkUnmarshal(b *testing.B) { | |
w := httptest.NewRecorder() | |
for n := 0; n < b.N; n++ { | |
r, err := http.NewRequest(http.MethodPost, "", strings.NewReader(body)) | |
if err != nil { | |
b.Fatal(err) | |
} | |
createMovieHandlerUnmarshal(w, r) | |
} | |
} | |
func BenchmarkDecoder(b *testing.B) { | |
w := httptest.NewRecorder() | |
for n := 0; n < b.N; n++ { | |
r, err := http.NewRequest(http.MethodPost, "", strings.NewReader(body)) | |
if err != nil { | |
b.Fatal(err) | |
} | |
createMovieHandlerDecoder(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment