golang 1.2.1在生产环境中应用应该注意的问题

LvanNeo · · 2017 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

golang 1.2.1的GC因为算法的问题,在实际应用过程中,对于长时间运行的daemon程序,确实很容易导致内存泄露,有人用cgo来手动管理内存,也有人用pool来管理buffer,这些都很麻烦,还是等1.3发布吧,在 golang 1.2.1中,如果注意一些坑,还是很容易写出稳定运行的程序。

1. 避免递归;

2.在for里面,把一些每次重复的操作提到外面,比如包的init方法中执行, 这些不必多说,比如初始化一个数据库连接,regexp.Compile等;

3. 函数返回,对于slice本身是引用传递,struct等比较大的对象,用指针,在for循环里面用完将指针赋值为nil,这一点非常重要;

The garbage collector will collect memory your program no longer has a pointer to.
To avoid leaking memory you just need to avoid holding on to pointers to memory you're no longer interested in using.

4.注意一些错误的写法,比如:

func parseFile(file string) string {
 f, err := os.Open(file) 

defer f.Close()
 if err != nil {
  fmt.Println(err)
  //os.Exit(1)
 }

正确的写法是:

func parseFile(file string) string {
 f, err := os.Open(file) 
 if err != nil {
  fmt.Println(err)
  return ""
  //os.Exit(1)
 }else{
  defer f.Close()
 }

这个问题很多初学者容易犯,非常容易导致cpu消耗大,甚至报错;

5. 减少对象的创建,尽量使用数组,struct可用做链表;

6. runtime.GC()没有什么用,go每2分钟执行一次垃圾回收;

> What is it used for? It should use in what situation? 

For example, before running a benchmark. But the runtime is free to 
ignore the call or postpone performing the real GC to any later time 
so it's a hint at best. 

> It is useful to avoid memory leaks? 

No. But it can in theory exchange longer GC pauses for more of shorter 
ones and also lower the total used memory - for some programs and it 
may be a win for them. 

See also: http://golang.org/pkg/runtime/debug/#FreeOSMemory 

7. 程序写完跑一段时间,用go自带的性能分析工具pprof分析heap,cpu等,尽快发现问题;

8. 运行发现cpu消耗高,内存持续上涨怎么办, 写个程序定时killall,或者crontab执行,再慢慢调优;


原文:http://blog.csdn.net/yxw2014/article/details/22283039


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:LvanNeo

查看原文:golang 1.2.1在生产环境中应用应该注意的问题

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2017 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传