Sync Pool

  • Create and make available pool of things for use.
  • 對於需要很多重複分配,GC 的地方. 可以使用 sync.Pool.
  • sync.Pool 可以將暫時不用的對象緩存起來, 待下次需要的時候直接使用, 不用在經過內存分配, 重複使用對象的內存, 減少GC, 提升效能
  • 是協程安全, 設置好 New function, 使用 Get() Put() 這可以取/還對象
b := bufPool.Get().(*bytes.Buffer)
bufPool.Pub(b)

Exercises

No Pool

https://go.dev/play/p/OnO91TiPAml

package main

import (
    "bytes"
    "io"
    "os"
    "time"
)

func log(w io.Writer, val string) {
    var b bytes.Buffer

    b.WriteString(time.Now().Format("15:04:05"))
    b.WriteString(" : ")
    b.WriteString(val)
    b.WriteString("\n")

    w.Write(b.Bytes())
}

func main() {
    log(os.Stdout, "debug-string1")
    log(os.Stdout, "debug-string2")
}

sync.Pool

https://go.dev/play/p/k3XnhjCwtQA

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
    "sync"
    "time"
)

// create pool of bytes.Buffers which can be reused.
var bufPool = sync.Pool{
    New: func() interface{} {
        fmt.Println("allocate new bytes.Buffer")
        return new(bytes.Buffer)
    },
}

func log(w io.Writer, val string) {
    b := bufPool.Get().(*bytes.Buffer)
    // 因為在實際的並發使用場景中,無法保證這種順序,最好的做法是在 Put 前,將對象清空。
    b.Reset()

    b.WriteString(time.Now().Format("15:04:05"))
    b.WriteString(" : ")
    b.WriteString(val)
    b.WriteString("\n")

    w.Write(b.Bytes())
    bufPool.Put(b)
}

func main() {
    log(os.Stdout, "debug-string1")
    log(os.Stdout, "debug-string2")
}
Get()

Image

Put()

Image

Referenct

© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""