当前位置:网站首页>Using easyjson to improve the efficiency of serialization transmission
Using easyjson to improve the efficiency of serialization transmission
2022-06-24 17:22:00 【Johns】
Introduce
easyjson It is used to do sth quickly json Serialization and deserialization toolkit , By giving us the struct Generate methods to implement... Without reflection json serialize , Than golang The original json tool kit , Performance can be improved 2~3 times .
go The reflection of language api The design is not like java You can also get the field value of the object directly , Instead, use it every time reflect.ValueOf(v) To create a new field object and then get the field value , This will add an extra GC The burden of , At the same time, the efficiency is also low . By traversing fields to assemble field contents, unnecessary object creation can be avoided , And it will be more efficient .
Use
- install
go get -u github.com/mailru/easyjson/ go install github.com/mailru/easyjson/easyjsonor go build -o easyjson github.com/mailru/easyjson/easyjson
Check if the installation is successful
~bash>easyjson
Usage of easyjson:
-all
generate marshaler/unmarshalers for all structs in a file
-build_tags string
build tags to add to generated file
-byte
use simple bytes instead of Base64Bytes for slice of bytes
-disable_members_unescape
.....- Entity class service.go
//easyjson:json
type MultiplyRequest struct {
A int `json:"a"`
B int `json:"b"`
}
//easyjson:json
type MultiplyResponse struct {
Res int `json:"res"`
}- Go to the command line , Switch to current go Enter the directory where the file is located :easyjson -all service.go Will generate service_easyjson.go, This file provides methods for serialization and deserialization .
func easyjson8d893851DecodeGoKitMicroservicePb3(in *jlexer.Lexer, out *MultiplyRequest) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeFieldName(false)
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
case "a":
out.A = int64(in.Int64())
case "b":
out.B = int64(in.Int64())
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
}We can see very clearly that Marshal The specific process of .
- Formal code replacement transport.go
func decodeMultiplyRequest(ctx context.Context, r *http.Request) (interface{}, error) {
bs, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
fmt.Printf(string(bs))
req := &MultiplyRequest{}
err = req.UnmarshalJSON(bs)
if err != nil {
return nil, err
}
return nil, nil
}
func decodeMultiplyRequest(ctx context.Context, r *http.Request) (interface{}, error) {
bs, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
fmt.Printf(string(bs))
req := &MultiplyRequest{}
err = req.UnmarshalJSON(bs)
if err != nil {
return nil, err
}
return nil, nil
}
// decode response
func encodeMultiplyResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
if f, ok := response.(endpoint.Failer); ok && f.Failed() != nil {
errorEncoder(ctx, f.Failed(), w)
return nil
}
resp := response.(*pb.MultiplyResponse)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
bs, err := resp.MarshalJSON()
if err != nil {
return err
}
w.Write(bs)
return nil
}边栏推荐
- H265 video streaming web page without plug-in player easywasmlayer Troubleshooting and solution of JS unable to set cover photo
- Development analysis of main chain system
- Example description and case of ansible playbook automated cluster server management
- NFT元宇宙源码搭建解析与介绍
- Release! Tencent IOA and Tencent sky screen were selected into the first batch of certified products of domestic digital trusted services
- Use cloud development to make a login free resource navigation applet!
- AFG EDI requirements details
- [kotlin] constructor summary
- Game business DDoS attack and defense confrontation case sharing
- liver failure! My friend made a programming navigation website!
猜你喜欢

MySQL learning -- table structure of SQL test questions

Why do you develop middleware when you are young? "You can choose your own way"
Using consistent hash algorithm in Presto to enhance the data cache locality of dynamic clusters

Daily algorithm & interview questions, 28 days of special training in large factories - the 15th day (string)
![[leetcode108] convert an ordered array into a binary search tree (medium order traversal)](/img/e1/0fac59a531040d74fd7531e2840eb5.jpg)
[leetcode108] convert an ordered array into a binary search tree (medium order traversal)
随机推荐
Robot toolbox matlab robotics toolbox
Pagoda activities, team members can enjoy a lightweight server 1 core 2g5m 28 yuan for two years
liver failure! My friend made a programming navigation website!
How much does the page length affect the ranking?
Introduction to visual studio shortcut keys and advanced gameplay
How to get the response body content in gin?
跟着Vam一起学习Typescript(第一期)
AFG EDI requirements details
实现TypeScript运行时类型检查
One article combs multi task learning (mmoe/ple/dupn/essm, etc.)
Memory alignment in golang
Implement typescript runtime type checking
What is the reason for the worse website SEO ranking?
Audio knowledge (I)
A tutorial on how the zblog system obtains user related information based on user ID
Complete the log service CLS questionnaire in 1 minute and receive the Tencent cloud 30 yuan threshold free voucher ~
Collect tke logs through daemonset CRD
让UPS“印象派用户”重新认识可靠性
Let ups "Impressionist users" re understand reliability
[kotlin] constructor summary