Thanks to visit codestin.com
Credit goes to pkg.go.dev

pool

package
v1.6.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 27, 2024 License: Apache-2.0, MIT Imports: 2 Imported by: 0

README

pbytes

The initial code cloned from https://github.com/gobwas/pool

Problem

https://research.swtch.com/interfaces

If you try to assign a []byte to an interface{}, the compiler will generate additional conversion code runtime.convTslice and cause memory allocation.

func main() {
	buffer := make([]byte, 0, 64)
	var o interface{} = buffer // CALL    runtime.convTslice(SB)
	fmt.Println(o)
}

convTslice source code https://go.dev/src/runtime/iface.go

func convTslice(val []byte) (x unsafe.Pointer) {
	// Note: this must work for any element type, not just byte.
	if (*slice)(unsafe.Pointer(&val)).array == nil {
		x = unsafe.Pointer(&zeroVal[0])
	} else {
		x = mallocgc(unsafe.Sizeof(val), sliceType, true)
		*(*[]byte)(x) = val
	}
	return
}

(*sync.Pool).Put source code https://go.dev/src/sync/pool.go

// Put adds x to the pool
func (p *Pool) Put(x any) {
    ...
}
var buf = make([]byte, 0, 16)
// equals:
// var x interface{} = buf // CALL    runtime.convTslice(SB)
// pool.Put(x)
pool.Put(buf) 

Resolved

Don't put the []byte into sync.Pool, to resolve the problems, put *[]byte instead.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Pool

type Pool[T any] struct {
	// contains filtered or unexported fields
}

Pool contains logic of reusing objects distinguishable by size in generic way.

func New

func New[T any](max int) *Pool[T]

New creates new Pool that reuses objects which size

func (*Pool[T]) Get

func (p *Pool[T]) Get(size int) (T, int)

Get pulls object whose generic size is at least of given size. It also returns a real size of x for further pass to Put() even if x is nil. Note that size could be ceiled to the next power of two.

func (*Pool[T]) Put

func (p *Pool[T]) Put(x T, size int)

Put takes x and its size for future reuse.

Directories

Path Synopsis
internal
Package pbytes contains tools for pooling byte pool.
Package pbytes contains tools for pooling byte pool.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL