当前位置:网站首页>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
边栏推荐
- Jerry's test mic energy automatic recording automatic playback reference [article]
- MIT-6.824-lab4A-2022(万字讲解-代码构建)
- Rasa 3. X learning series - it is a great honor to be a source code contributor of Rasa contributors, and to build and share the rasa community with rasa source code contributors all over the world!
- Explain kubernetes backup and recovery tools velero | learn more about carina series phase III
- 4个不可不知的“安全左移”的理由
- The project manager needs to look at six characteristics to build a team
- 杰理之TIMER0 用默认的 PA13 来检测脉宽【篇】
- 2022 coal mine gas drainage operation certificate examination questions and simulation examination
- Use of kotlin arrays, collections, and maps
- kotlin 组合挂起函数
猜你喜欢

Getting to know cloud native security for the first time: the best guarantee in the cloud Era

Usage of multimeter

Tupu software is the digital twin of offshore wind power, striving to be the first

远程办公之:在家露营办公小工具| 社区征文

居家办公更要高效-自动化办公完美提升摸鱼时间 | 社区征文

遠程辦公之:在家露營辦公小工具| 社區征文

AutoRF:从单视角观察中学习3D物体辐射场(CVPR 2022)

Home office should be more efficient - automated office perfectly improves fishing time | community essay solicitation
![[R language data science] (XIV): random variables and basic statistics](/img/87/3606041a588ecc615eb8013cdf9fb1.png)
[R language data science] (XIV): random variables and basic statistics

AntD checkbox,限制选中数量
随机推荐
Operation of simulated examination platform of examination question bank for B certificate of Jiangxi provincial safety officer in 2022
从谭浩强《C程序设计》上摘录的ASCII码表(常用字符与ASCII代码对照表)
Docker安装redis
The research on the report "market insight into China's database security capabilities, 2022" was officially launched
项目经理搭建团队,需要看6个特征
《中国数据库安全能力市场洞察,2022》报告研究正式启动
PM should also learn to reflect every day
Jerry's test mic energy automatic recording automatic playback reference [article]
Télétravail: Camping à la maison gadgets de bureau | rédaction communautaire
Tupu software is the digital twin of offshore wind power, striving to be the first
谷歌WayMo提出R4D: 采用参考目标做远程距离估计
【sdx62】WCN685X IPA不生效问题分析及解决方案
【sdx62】WCN685X IPA注册失败问题分析及解决方案
kotlin 组合挂起函数
数商云:加强供应商管理,助推航空运输企业与供应商高效协同
群晖向阿里云OSS同步
Daily question 8-515 Find the maximum value in each tree row
Operation of simulated test question bank and simulated test platform for safety production management personnel of fireworks and firecrackers production units in 2022
Android kotlin Encyclopedia
HarmonyOS-3