微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)
}

正确的写法是:

//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

原文地址:https://www.jb51.cc/go/190982.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐