goapiperf/jsoniter/jsonBenchmark_test.go

84 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-09-19 20:54:54 +03:00
package main
import (
"encoding/json"
"testing"
jsoniter "github.com/json-iterator/go"
)
var jsonData = []byte(`{
"name": "Alice",
"age": 30,
"email": "alice@example.com",
"address": {
"street": "123 Maple Street",
"city": "Wonderland",
"postal_code": "12345"
},
"phones": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
],
"is_active": true,
"metadata": {
"created_at": "2024-08-16T10:00:00Z",
"updated_at": "2024-08-17T10:00:00Z"
},
"tags": ["developer", "golang", "openai"]
}`)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
Address Address
Phones []Phone
IsActive bool `json:"is_active"`
Metadata Metadata
Tags []string
}
type Phone struct {
Type string `json:"type"`
Number string `json:"number"`
}
type Address struct {
Street string `json:"street"`
City string `json:"city"`
PostalCode string `json:"postal_code"`
}
type Metadata struct {
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
func BenchmarkEncodingJSON(b *testing.B) {
for i := 0; i < b.N; i++ {
var user User
err := json.Unmarshal(jsonData, &user)
if err != nil {
b.Fatalf("Failed to unmarshal: %v", err)
}
}
}
func BenchmarkJSONIter(b *testing.B) {
json := jsoniter.ConfigCompatibleWithStandardLibrary
for i := 0; i < b.N; i++ {
var user User
err := json.Unmarshal(jsonData, &user)
if err != nil {
b.Fatalf("Failed to unmarshal: %v", err)
}
}
}