gpool

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2023 License: MIT Imports: 1 Imported by: 0

README

gpool

Generic wrapper for sync.Pool in Go

Usage

int64 type

p := Pool[int64]{New: func() int64 { return 42 }}
x := p.Get()
defer p.Put(x)
fmt.Printf("x = (%T) %d", x, x)
// Output: x = (int64) 42

string type

p := Pool[string]{New: func() string { return "foo" }}
x := p.Get()
defer p.Put(x)
fmt.Printf("x = (%T) %s", x, x)
// Output: x = (string) foo

Benchmarks

% go test -bench=. -benchmem ./...
goos: darwin
goarch: arm64
pkg: github.com/sv-tools/gpool
BenchmarkSyncPool-8     699275571                1.614 ns/op           0 B/op          0 allocs/op
BenchmarkPool-8         647708158                1.732 ns/op           0 B/op          0 allocs/op

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Pool

type Pool[T any] struct {

	// New optionally specifies a function to generate
	// a value when Get would otherwise return nil.
	// It may not be changed concurrently with calls to Get.
	New func() T
	// contains filtered or unexported fields
}

Pool is generic drop-in replacement of `sync.Pool`

Example (Int64)
p := Pool[int64]{New: func() int64 { return 42 }}
x := p.Get()
defer p.Put(x)
fmt.Printf("x = (%T) %d", x, x)
Output:

x = (int64) 42
Example (String)
p := Pool[string]{New: func() string { return "foo" }}
x := p.Get()
defer p.Put(x)
fmt.Printf("x = (%T) %s", x, x)
Output:

x = (string) foo

func (*Pool[T]) Get

func (p *Pool[T]) Get() (item T)

Get selects an arbitrary item from the Pool, removes it from the Pool, and returns it to the caller. Get may choose to ignore the pool and treat it as empty. Callers should not assume any relation between values passed to Put and the values returned by Get.

If Get would otherwise return nil and p.New is non-nil, Get returns the result of calling p.New.

func (*Pool[T]) Put

func (p *Pool[T]) Put(x T)

Put adds x to the pool.

Jump to

Keyboard shortcuts

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