github.com/blend/go-sdk@v1.20220411.3/bufferutil/pool.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package bufferutil
     9  
    10  import (
    11  	"bytes"
    12  	"sync"
    13  )
    14  
    15  /*
    16  NewPool returns a new Pool, which returns bytes buffers pre-sized to a given minimum size.
    17  
    18  The purpose of a buffer pool is to reduce the number of gc collections incurred when using bytes buffers
    19  repeatedly; instead of marking the buffer as to be collected, it is returned to the pool to be re-used.
    20  
    21  Example:
    22  
    23  	pool := bufferutil.NewPool(1024) // pre-allocate 1024 bytes per buffer.
    24  
    25  	func() {
    26  		buf := pool.Get()
    27  		defer pool.Put(buf)
    28  
    29  		// do things with the buffer ...
    30  	}()
    31  
    32  */
    33  func NewPool(bufferSize int) *Pool {
    34  	return &Pool{
    35  		Pool: sync.Pool{New: func() interface{} {
    36  			b := bytes.NewBuffer(make([]byte, bufferSize))
    37  			b.Reset()
    38  			return b
    39  		}},
    40  	}
    41  }
    42  
    43  // Pool is a sync.Pool of bytes.Buffer.
    44  type Pool struct {
    45  	sync.Pool
    46  }
    47  
    48  // Get returns a pooled bytes.Buffer instance.
    49  func (p *Pool) Get() *bytes.Buffer {
    50  	return p.Pool.Get().(*bytes.Buffer)
    51  }
    52  
    53  // Put returns the pooled instance.
    54  func (p *Pool) Put(b *bytes.Buffer) {
    55  	b.Reset()
    56  	p.Pool.Put(b)
    57  }