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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值