lfu

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2023 License: Apache-2.0, MIT Imports: 4 Imported by: 0

README

LFU

This is a Least Frequently Used cache backed by a generic doubly linked list with O(1) time complexity.

When to use

You would typically use an LFU cache when:

  • Capacity of cache is far lower than data available.
  • Entries being used are high frequency compared to others over time.

Both above will prevent the most frequently use data from flapping in and out of the cache.

Usage

package main

import (
	"fmt"
	"github.com/go-playground/cache/lfu"
	"time"
)

func main() {
	cache := lfu.New[string, string](100).MaxAge(time.Hour).HitFn(func(key string, value string) {
		fmt.Printf("Hit Key: %s Value %s\n", key, value)
	}).Build()
	cache.Set("a", "b")
	cache.Set("c", "d")

	option := cache.Get("a")
	if option.IsNone() {
		return
	}
	fmt.Println("result:", option.Unwrap())
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New[K comparable, V any](capacity int) *builder[K, V]

New initializes a builder to create an LFU cache.

Types

type LFU

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

LFU is a configured least frequently used cache ready for use.

func (*LFU[K, V]) Capacity

func (cache *LFU[K, V]) Capacity() (capacity int)

Capacity returns the current configured capacity of the cache.

func (*LFU[K, V]) Clear

func (cache *LFU[K, V]) Clear()

Clear empties the cache.

func (*LFU[K, V]) Get

func (cache *LFU[K, V]) Get(key K) (result optionext.Option[V])

Get attempts to find an existing cache entry by key. It returns an Option you must check before using the underlying value.

func (*LFU[K, V]) Len

func (cache *LFU[K, V]) Len() (length int)

Len returns the current size of the cache. The result will include items that may be expired past the max age as they are passively expired.

func (*LFU[K, V]) Remove

func (cache *LFU[K, V]) Remove(key K)

Remove removes the item matching the provided key from the cache, if not present is a noop.

func (*LFU[K, V]) Set

func (cache *LFU[K, V]) Set(key K, value V)

Set sets an item into the cache. It will replace the current entry if there is one.

Jump to

Keyboard shortcuts

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