当前位置:网站首页>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
边栏推荐
- Operation of simulated examination platform for examination questions of coal production and operation units (safety production management personnel) in 2022
- Jerry's seamless looping [chapter]
- #21Set经典案例
- [5g NR] 5g NR system architecture
- 食品饮料行业渠道商管理系统解决方案:实现渠道数字化营销布局
- Kotlin language features
- npm包【详解】(内含npm包的开发、发布、安装、更新、搜索、卸载、查看、版本号更新规则、package.json详解等)
- The research on the report "market insight into China's database security capabilities, 2022" was officially launched
- Return to new list
- 融云通信“三板斧”,“砍”到了银行的心坎上
猜你喜欢
![NPM package [details] (including NPM package development, release, installation, update, search, uninstall, view, version number update rules, package.json details, etc.)](/img/b0/85ac6274b239e42c9543fa296df456.png)
NPM package [details] (including NPM package development, release, installation, update, search, uninstall, view, version number update rules, package.json details, etc.)

One click to generate University, major and even admission probability. Is it so magical for AI to fill in volunteer cards?

【5G NR】5G NR系统架构

Gatling performance test

The first open source MySQL HTAP database in China will be released soon, and the three highlights will be notified in advance

智慧园区SaaS管理系统解决方案:赋能园区实现信息化、数字化管理
![Jerry's serial port receiving IO needs to set the digital function [chapter]](/img/04/48e7da42101a53827463d479952f67.png)
Jerry's serial port receiving IO needs to set the digital function [chapter]

Rasa 3.x 学习系列-非常荣幸成为 Rasa contributors 源码贡献者,和全世界的Rasa源码贡献者共建共享Rasa社区!

Mit-6.824-lab4a-2022 (ten thousand words explanation - code construction)

位于相同的分布式端口组但不同主机上的虚拟机无法互相通信
随机推荐
The real project managers are all closed-loop masters!
HarmonyOS.2
2022年施工升降机司机(建筑特殊工种)考试试题及在线模拟考试
[sdx62] wcn685x IPA failure analysis and solution
Operation of simulated examination platform of examination question bank for B certificate of Jiangxi provincial safety officer in 2022
kotlin 共享可变状态和并发性
Unity 热力图建立方法
Antd checkbox, limit the selected quantity
MIT-6.824-lab4A-2022(万字讲解-代码构建)
win10系统问题
国内首款开源MySQL HTAP数据库即将发布,三大看点提前告知
AntD checkbox,限制选中数量
Ti Xing Shu'an joined the dragon lizard community to jointly create a network security ecosystem
项目经理搭建团队,需要看6个特征
90%的项目经理都跳过的坑,你现在还在坑里吗?
Home office should be more efficient - automated office perfectly improves fishing time | community essay solicitation
Docker installation redis
记录一次Mongotemplate的And和Or的各种套
Android kotlin Encyclopedia
杰理之串口接收 IO 需要设置数字功能【篇】