对象池化

package main

import (
    "log"
    "time"
)

func main() {

    size := (1 << 23)

    start := time.Now()
    for i := 0; i < size; i++ {
        data := make([]byte, 0, (1 << 15))
        _ = data
    }

    d := time.Now().Sub(start)
    log.Println("without pool", d)

}

添加一个bytes pool

type bytePool struct {
    c     chan []byte
    width int
}

func NewBytePool(size, width int) (bp *bytePool) {
    return &bytePool{
        c:     make(chan []byte, size),
        width: width,
    }
}

func (bp *bytePool) Get() (b []byte) {
    select {
    case b = <-bp.c:
        //do nothing

    default:
        b = make([]byte, 0, bp.width)

    }
    return
}

func (bp *bytePool) Put(b []byte) {
    select {
    case bp.c <- b:
        //return back
    default:
        //discard bytes
    }
    return
}

主程序变为

package main

import (
    "log"
    "time"
)

func main() {

    size := (1 << 23)

    start := time.Now()
    for i := 0; i < size; i++ {
        data := make([]byte, 0, (1 << 15))
        _ = data
    }

    d := time.Now().Sub(start)
    log.Println("without pool", d)

    bp := NewBytePool((1 << 20), (1 << 15))

    start = time.Now()
    for i := 0; i < size; i++ {
        data := bp.Get()
        _ = data
        bp.Put(data)
    }

    d = time.Now().Sub(start)
    log.Println("with pool", d, getc, newc)

}
// 2018/04/24 18:37:21 without pool 8.784228302s
// 2018/04/24 18:37:22 with pool 713.31206ms