dongnguyenltqb
1/1/2020 - 6:35 AM

proto_bench.go

package user

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/golang/protobuf/proto"
)

type Contact struct {
	PhoneNumber string `json:"phone_number`
	Country     string `json:"country"`
}

type User struct {
	FirstName string    `json:"first_name`
	LastName  string    `json:"last_name"`
	Contact   []Contact `json:"contact"`
}

func Benchmark() {
	n := 5000000
	fmt.Println("JSON - START")
	now := time.Now()

	for i := 1; i <= n; i++ {
		u := User{
			FirstName: "Dong",
			LastName:  "Nguyen",
			Contact: []Contact{
				Contact{
					PhoneNumber: "039 390 1228",
					Country:     "Viet Nam",
				},
			},
		}
		binary, _ := json.Marshal(u)
		var v User
		json.Unmarshal(binary, &v)
	}
	fmt.Println("JSON - END :", time.Now().Sub(now))
	fmt.Println("PROTOBUF - START")
	now = time.Now()
	for i := 1; i <= n; i++ {
		u := &UserProtobuf{
			FirstName: "Dong",
			LastName:  "Nguyen",
			Contact: []*ContactProtobuf{
				&ContactProtobuf{
					PhoneNumber: "039 390 1228",
					Country:     "Viet Name",
				},
			},
		}
		binary, _ := proto.Marshal(u)
		var v UserProtobuf
		proto.Unmarshal(binary, &v)
	}
	fmt.Println("PROTOBUF - END :", time.Now().Sub(now))

}

package main

import "bench/user"

func main() {
	user.Benchmark()
}