lru

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2022 License: MIT Imports: 2 Imported by: 14

README

lru

Go Reference CI

Threadsafe GoLang LRU cache.

Example

import (
	"fmt"

	"github.com/floatdrop/lru"
)

func ExampleLRU() {
	cache := lru.New[string, int](256)

	cache.Set("Hello", 5)

	fmt.Println(*cache.Get("Hello"))
	// Output: 5
}

Benchmarks

floatdrop/lru:
    BenchmarkLRU_Rand-8   	 9373129	       124.4 ns/op	       8 B/op	       1 allocs/op
    BenchmarkLRU_Freq-8   	10124833	       120.3 ns/op	       8 B/op	       1 allocs/op

hashicorp/golang-lru:
    BenchmarkLRU_Rand-8   	 5992782	       195.8 ns/op	      76 B/op	       3 allocs/op
    BenchmarkLRU_Freq-8   	 6355358	       186.1 ns/op	      71 B/op	       3 allocs/op

Documentation

Overview

Package lru implements cache with least recent used eviction policy.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[K comparable, V any] interface {
	Get(key K) *V

	Set(key K, value V) *V
}

Cache defines minimal interface for all cache implementations, that requires two methods: Get and Set.

type LRU

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

LRU implements Cache interface with least recent used eviction policy.

Example
package main

import (
	"fmt"

	"github.com/floatdrop/lru"
)

func main() {
	cache := lru.New[string, int](256)

	cache.Set("Hello", 5)

	fmt.Println(*cache.Get("Hello"))
}
Output:

5

func New

func New[K comparable, V any](size int) *LRU[K, V]

New creates LRU cache with size capacity. Cache will preallocate size count of internal structures to avoid allocation in process.

func (*LRU[K, V]) Get

func (L *LRU[K, V]) Get(key K) *V

Get returns pointer to value for key, if value was in cache (nil returned otherwise).

func (*LRU[K, V]) Set

func (L *LRU[K, V]) Set(key K, value V) *V

Set inserts key value pair and returns evicted value, if cache was full. If cache size is less than 1 – method will always return reference to value (as if it was immediately evicted).

type Nop

type Nop[K comparable, V any] struct{}

Nop implements Cache interface, but does nothing inside (all sets are ignored, all get operations return nil).

func (*Nop[K, V]) Get

func (n *Nop[K, V]) Get(key K) *V

Get method of Nop cache always returns nil.

func (*Nop[K, V]) Set

func (n *Nop[K, V]) Set(key K, value V) *V

Set method of Nop cache always returns value pointer (as if it was immediately evicted).

Jump to

Keyboard shortcuts

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