当前位置:网站首页>Three efficient programming skills of go language
Three efficient programming skills of go language
2022-06-24 14:06:00 【The snow is merciless】
Click blue above “ Snowy and heartless ” Pay attention to me , Set a star , Read the article for the first time
Go Is a very good programming language . It is a way for you to really focus on your business , Don't worry too much about the language of the program itself , So you can write the application as soon as possible . For example, it has a relatively complete ecosystem , It can provide you with everything you need to get started .
But what? , It's not everything , There are some things we need to pay attention to . I wrote this article mainly to remind myself , Also some observations and conclusions . Of course , These are just tricks , It's not really a problem , Of course, if you notice them and use them in practice , It will benefit you very much , This is the difference between novice and veteran .
Do not use Logrus
This is really about generics . because Go Language is a strongly typed static language , So you can't be like NodeJS perhaps PHP That bypasses data types . What if we still need to use generic types ? Such as Loger, perhaps ORM, Because only common types are used , To write universal code , Otherwise everyone has to write once .
Final , We can only use reflection . and Logrus Use reflection a lot , This results in a large number of allocation counts . Although usually not a big problem ( Depends on the code ), But performance is important , Especially on a large scale 、 In highly concurrent projects . Although this sounds like a very small optimization , But it's important to avoid reflection . If you see some code that can use structures regardless of type , It uses reflection and has an impact on performance .
for example ,Logrus Don't care about type , But apparently Go Need to know ( Final ).Logrus What shall I do? ? Use reflection to detect types , This is an expense .
log.WithFields(log.Fields{
"animal": myWhatever,
}).Info("A walrus appears")
So I would prefer zerolog, Of course zap Pretty good also . Both claim zero distribution , That's what we want , Because their performance impact is minimal .
Do not use encoding/json
When we need a function 、 Function , Many people recommend using the standard library . But in the standard library encoding/json Modules are an exception . In fact, it is the same as the above example ,encoding/json Using reflection , This leads to poor performance , And writing the return json Responsive API 、 Or micro services will cause losses .
For example, you can use Easyjson, It is very simple , It's also efficient. , It uses a code generator to create a structure that converts to json Required code , To minimize allocation . This is a manual build step , Is very boring . Interestingly json-iterator Also use reflection , But significantly faster , I suspect it's black magic .
Try not to goroutine Using closures in
such as , The following example code :
for i:=0;i<10;i++ {
go func() {
fmt.Println(i)
}()
}
Most people might expect this to print numbers 0 To 9, It's like delegating a task to goroutine It's like that .
But the actual result : According to the system , You will get oneortwo numbers and many 10.
Why is that? ? Closures can access the parent scope , So you can use variables directly . Although updated linters May warn you “ Variable closure capture ”, But it doesn't require you to redeclare the variable .
Go The performance reputation of is largely due to the execution of runtime optimizations , It tries to “ guess ” What do you want to do and optimize some execution paths . in the meantime , it “ Capture ” Variables and pass them to where they are needed in the most efficient way in theory ( for example , After completing some non concurrent operations to release some CPU After allocation on ). The result in this case is that the loop may start goroutines,goroutines May receive... From the parent scope very late i Value . There is no guarantee which... You will see when you execute this code multiple times , It could be numbers 10, It can also be other numbers .
If you do use closures for some reason , Be sure to pass variables i, Treat closures like every function .
Summary
There must be more than these three skills in programming practice , Explore and master them in practice , It can improve our programming ability , Let's write more optimized code .
This is an original article , Reprint with reference to , Welcome to scan code to pay attention to official account.
flysnow_orgOr websites https://www.flysnow.org/ , The first time to see the following wonderful articles . If you feel good , Please click on the bottom right corner of the article 「 Looking at 」, Thank you for your support .
—— Highlights ——
Do it Caddy( 13、 ... and )| Plug in development Caddyfile Parameters
Caddy actual combat ( Twelve )| Plug in development HelloWorld
Caddy actual combat ( 11、 ... and )| Caddyfile The beauty of design
Caddy actual combat ( Ten )| Build in one minute PHP The server
Caddy actual combat ( Nine )| Set header information to realize cross domain
Caddy actual combat ( 8、 ... and )| Using buffer to improve the performance of reverse proxy
Caddy actual combat ( 7、 ... and )| Health check in reverse proxy
Caddy actual combat ( 6、 ... and )| Load balancing in reverse proxy
Caddy actual combat ( 5、 ... and )| Configure reverse proxy
Caddy actual combat ( Four )| Use API management Caddy
Caddy actual combat ( 3、 ... and )| Caddyfile Quick start
Caddy actual combat ( Two )| Caddy The most complete tutorial of command line parameters
Caddy actual combat ( One )| Hosting your website , Just one command

Sweep yards attention
Share 、 give the thumbs-up 、 Watching is the greatest support
边栏推荐
- HarmonyOS.2
- 一键生成大学、专业甚至录取概率,AI填报志愿卡这么神奇?
- kotlin 协程上下文和调度器
- 在线文本实体抽取能力,助力应用解析海量文本数据
- HarmonyOS. two
- The first open source MySQL HTAP database in China will be released soon, and the three highlights will be notified in advance
- Jericho turns on shouting in all modes to increase mic automatic mute [chapter]
- npm包【详解】(内含npm包的开发、发布、安装、更新、搜索、卸载、查看、版本号更新规则、package.json详解等)
- 远程办公之:在家露营办公小工具| 社区征文
- 每日一题day8-515. 在每个树行中找最大值
猜你喜欢

2022 Quality Officer - Equipment direction - post skills (Quality Officer) recurrent training question bank and online simulation examination

HarmonyOS.2

如何在物联网低代码平台中进行任务管理?

Activity lifecycle

初识云原生安全:云时代的最佳保障

Activity生命周期

融云通信“三板斧”,“砍”到了银行的心坎上
![[5g NR] 5g NR system architecture](/img/78/6db70c18887c7a3920843d1cb4bdf3.png)
[5g NR] 5g NR system architecture

In the era of knowledge economy, it will teach you to do well in knowledge management

百度地图API绘制点及提示信息
随机推荐
In the era of knowledge economy, it will teach you to do well in knowledge management
kotlin 协程通道
【sdx62】WCN685X IPA注册失败问题分析及解决方案
4个不可不知的“安全左移”的理由
2022质量员-设备方向-通用基础(质量员)考试题及答案
2022 coal mine gas drainage operation certificate examination questions and simulation examination
kotlin 协程上下文和调度器
食品饮料行业渠道商管理系统解决方案:实现渠道数字化营销布局
项目经理搭建团队,需要看6个特征
**Puzzling little problem in unity - light and sky box
Promotion of Project Manager
Seven challenges faced by data scientists and Solutions
JS remove string spaces
记录一次Mongotemplate的And和Or的各种套
Return to new list
2022 Quality Officer - Equipment direction - post skills (Quality Officer) recurrent training question bank and online simulation examination
返回新列表
2022煤矿瓦斯抽采操作证考试题及模拟考试
[sdx62] wcn685x IPA failure analysis and solution
Activity生命周期