当前位置:网站首页>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
}边栏推荐
- A comprehensive understanding of fiber to home FTTH and optical splitter
- H265 video streaming web page without plug-in player easywasmlayer Troubleshooting and solution of JS unable to set cover photo
- "Gambler" bubble Matt turns around
- How important is it to document the project? I was chosen by the top 100 up leaders and stood up again
- Ramda's little-known side
- How to troubleshoot and solve the problem that the ultra-low delay security live broadcast system webrtc client plays no audio in the browser?
- Robot toolbox matlab robotics toolbox
- [version upgrade] Tencent cloud firewall version 2.1.0 was officially released!
- TCB series learning articles - using redis extension in cloud functions
- Tencent released "warehouse express" and issued "ID card" for each commodity!
猜你喜欢

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

MySQL learning -- table structure of SQL test questions

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)
随机推荐
Use cloud development to make a login free resource navigation applet!
How to compile and debug go runtime source code
Issue 003 how to detect whether a sticky positioned element is in a pinned state
Is CICC securities reliable? Is it legal? Is it safe to open a stock account?
Explanation of MySQL indexing principle
Management system permission design
Cloud native monitoring via blackbox_ Exporter monitoring website
Bypass kernel function pointer integrity check
## Kubernetes集群中流量暴露的几种方案 Kubernetes集群中流量暴露的几种方案
主链系统发展解析
Collect tke logs through daemonset CRD
Zblog determines whether a plug-in installs the enabled built-in function code
Live broadcast Preview - on April 1, I made an appointment with you to explore tcapulusdb with Tencent cloud
"Competition" and "opportunity" hidden in security operation in the cloud Era
What is the problem that the data is not displayed on the login web page after the configuration of the RTSP video security intelligent monitoring system easynvr is completed
[version upgrade] Tencent cloud firewall version 2.1.0 was officially released!
Release! Tencent IOA and Tencent sky screen were selected into the first batch of certified products of domestic digital trusted services
Radiology: contralateral preoperative resting state MRI functional network integration is related to the surgical results of temporal lobe epilepsy
How important is it to document the project? I was chosen by the top 100 up leaders and stood up again
liver failure! My friend made a programming navigation website!