Go语言学习技巧之如何合理使用Pool

栏目: 编程语言 · Go · 发布时间: 7年前

内容简介:这篇文章主要给大家介绍了关于Go语言学习技巧之如何合理使用Pool的相关资料,Pool用于存储那些被分配了但是没有被使用,而未来可能会使用的值,以减小垃圾回收的压力。文中通过示例代码介绍的非常详细,需要的朋友可以参考下。

前言

Go 1.3 的sync包中加入一个新特性:Pool。

这个类设计的目的是用来保存和复用临时对象,以减少内存分配,降低CG压力。

type Pool 
func (p *Pool) Get() interface{} 
func (p *Pool) Put(x interface{}) 
New func() interface{} 

垃圾回收一直是 Go 语言的一块心病,在它执行垃圾回收的时间中,你很难做什么。

在垃圾回收压力大的服务中,GC占据的CPU有可能超过2%,造成的Pause经常超过2ms。垃圾严重的时候,秒级的GC也出现过。

如果经常临时使用一些大型结构体,可以用Pool来减少GC。

示例代码

package main
import (
 "fmt"
 "sync"
 "time"
)
type structR6 struct {
 B1 [100000]int
}
var r6Pool = sync.Pool{
 New: func() interface{} {
 return new(structR6)
 },
}
func usePool() {
 startTime := time.Now()
 for i := 0; i < 10000; i++ {
 sr6 := r6Pool.Get().(*structR6)
 sr6.B1[0] = 0
 r6Pool.Put(sr6)
 }
 fmt.Println("pool Used:", time.Since(startTime))
}
func standard() {
 startTime := time.Now()
 for i := 0; i < 10000; i++ {
 var sr6 structR6
 sr6.B1[0] = 0
 }
 fmt.Println("standard Used:", time.Since(startTime))
}
func main() {
 standard()
 usePool()
}

一个含有100000个int值的结构体,在标准方法中,每次均新建,重复10000次,一共需要耗费193ms;

如果用完的struct可以废物利用,放回pool中。需要新的结构体的时候,尝试去pool中取,而不是重新生成,重复10000次仅需要693us。

这样简单的操作,却节约了99.65%的时间,也节约了各方面的资源。最重要的是它可以有效减少GC CPU和GC Pause。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Numerical Methods and Methods of Approximation in Science and En

Numerical Methods and Methods of Approximation in Science and En

Karan Surana / CRC Press / 2018-10-31

ABOUT THIS BOOK Numerical Methods and Methods of Approximation in Science and Engineering prepares students and other readers for advanced studies involving applied numerical and computational anal......一起来看看 《Numerical Methods and Methods of Approximation in Science and En》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具