weakmap

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2024 License: CC0-1.0 Imports: 4 Imported by: 0

README

weakmap

Go Reference

Package weakmap implements a weak map for Go without unsafe or pointer magic. Instead, it uses finalizers to hook into garbage collection cycles and evicts old entries based on a combination of the least-recently-used (LRU) policy and memory pressure reported by the runtime.

go get github.com/ammario/weakmap@master

See https://github.com/golang/go/issues/43615 for the state of the debate of weak references in Go.

Basic Usage

The API should be familiar to anyone that's used a map:

// The default value is good to use.
m := weakmap.Map[string, int]{}
m.Set("pi", 3.14)

// 3.14, true
v, ok := m.Get("pi")

Eviction

Cache eviction occurs automatically when the GC runs. The number of removed entries is proportional to the program's memory pressure. Memory pressure is defined as the ratio of /memory/classes/heap/objects:bytes to /memory/classes/total:bytes.

Documentation

Overview

Package weakmap implements a weak reference map in Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Map

type Map[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map implements a LRU weak map safe for concurrent use. The zero value is an empty map ready for use.

When the GC runs, half of the least recently used entries are evicted.

func (*Map[K, V]) Delete

func (l *Map[K, V]) Delete(key K)

Delete removes an entry from the cache, returning cost savings.

func (*Map[K, V]) Do

func (l *Map[K, V]) Do(key K, fn func() (V, error)) (V, error)

Do is a helper that retrieves a value from the cache, if it exists, and calls the provided function to compute the value if it does not.

func (*Map[K, V]) Get

func (l *Map[K, V]) Get(key K) (v V, exists bool)

Get retrieves a value from the cache, if it exists.

func (*Map[K, V]) Len

func (l *Map[K, V]) Len() int

func (*Map[K, V]) Set

func (l *Map[K, V]) Set(key K, v V)

Set adds a new value to the cache. Set may also be used to bump a value to the top of the cache.

Directories

Path Synopsis
example
gctest command
internal
doublelist
Package doublelist implements a doubly-linked list.
Package doublelist implements a doubly-linked list.

Jump to

Keyboard shortcuts

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