go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/buffer_pool.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package web
     9  
    10  import (
    11  	"bytes"
    12  	"sync"
    13  )
    14  
    15  /*
    16  NewBufferPool 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.NewBufferPool(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  func NewBufferPool(defaultBufferSize int) *BufferPool {
    33  	return &BufferPool{
    34  		Pool: sync.Pool{New: func() interface{} {
    35  			b := bytes.NewBuffer(make([]byte, defaultBufferSize))
    36  			b.Reset()
    37  			return b
    38  		}},
    39  	}
    40  }
    41  
    42  // BufferPool is a sync.Pool of bytes.Buffer.
    43  type BufferPool struct {
    44  	sync.Pool
    45  }
    46  
    47  // Get returns a pooled bytes.Buffer instance.
    48  func (p *BufferPool) Get() *bytes.Buffer {
    49  	return p.Pool.Get().(*bytes.Buffer)
    50  }
    51  
    52  // Put returns the pooled instance.
    53  func (p *BufferPool) Put(b *bytes.Buffer) {
    54  	b.Reset()
    55  	p.Pool.Put(b)
    56  }