dongyuan1983 2018-06-14 07:01
浏览 158
已采纳

sync.Pool比使用channel慢得多,那么为什么要使用sync.Pool?

I read sync.Pool design, but find it is two logic, why we need localPool to solve lock compete. We can just use chan to implement one.

Using channel is 4x times faster than sync.pool!

Besides pool can clear object, what advantage does it have?

This is the pool implementation and benchmarking code:

package client

import (
    "runtime"
    "sync"
    "testing"
)

type MPool chan interface{}


type A struct {
    s        string
    b        int
    overflow *[2]*[]*string 

}

var p = sync.Pool{
    New: func() interface{} { return new(A) },
}

var mp MPool = make(chan interface{}, 100)

func get() interface{} {
    select {
    case r := <-mp:
        return r
    default:
        return new(A)
    }
}

func put(a interface{}) {
    select {
    case mp <- a:
    default:
    }
    return
}

func pool() {
    a := p.Get()
    p.Put(a)
}


func init() {
    runtime.GOMAXPROCS(8)
}

func BenchmarkName(b *testing.B) {
    for i := 0; i < 20; i++ {
        p.Put(new(A))
    }
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        for i := 0; i < 100; i++ {
            go func() {
                p.Put(p.Get())
            }()
        }
    }
}

func BenchmarkNotPool(b *testing.B) {
    for i := 0; i < 20; i++ {
        put(new(A))
    }
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        for i := 0; i < 100; i++ {
            a := get()
            put(a)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dongnaota6386 2018-06-14 07:15
    关注

    You are not benchmarking the same thing, so you can't compare the results.

    BenchmarkName() launches goroutines which have significant overheard and you don't even wait for those goroutines to finish, while BenchmarkNotPool() just gets and puts an object in the pool in the same goroutine.

    If you modify BenchmarkName() to do the same, the benchmark results actually show it's the other way: sync.Pool is more than 3 times faster, which is true, so that's its use / advantage.

    func BenchmarkName(b *testing.B) {
        for i := 0; i < 20; i++ {
            p.Put(new(A))
        }
        b.ResetTimer()
        for i := 0; i < b.N; i++ {
            for i := 0; i < 100; i++ {
                p.Put(p.Get())
            }
        }
    }
    

    Results:

    BenchmarkName-8           500000              2453 ns/op
    BenchmarkNotPool-8        200000              7984 ns/op
    

    Also see related question: How to implement Memory Pooling in Golang

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料