您的位置:首页 > 编程语言 > Go语言

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

2014-04-26 10:26 274 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: