github.com/lrita/cache@v1.0.1/README.md (about)

     1  [![Build Status](https://travis-ci.org/lrita/cache.svg?branch=master)](https://travis-ci.org/lrita/cache) [![GoDoc](https://godoc.org/github.com/lrita/cache?status.png)](https://godoc.org/github.com/lrita/cache) [![codecov](https://codecov.io/gh/lrita/cache/branch/master/graph/badge.svg)](https://codecov.io/gh/lrita/cache)
     2  
     3  # Cache
     4  
     5  Cache is a set of temporary objects that may be individually saved and
     6  retrieved.
     7  
     8  A Cache is safe for use by multiple goroutines simultaneously.
     9  
    10  Cache's purpose is to cache allocated but unused items for later reuse,
    11  relieving pressure on the garbage collector. That is, it makes it easy to
    12  build efficient, thread-safe free lists. However, it is not suitable for all
    13  free lists.
    14  
    15  An appropriate use of a Cache is to manage a group of temporary items
    16  silently shared among and potentially reused by concurrent independent
    17  clients of a package. Cache provides a way to amortize allocation overhead
    18  across many clients.
    19  
    20  The difference with std-lib sync.Pool is that the items in Cache does not be
    21  deallocated by GC, and there are multi slot in per-P storage and per-NUMA
    22  node storage. The free list in Cache maintained as parts of a long-lived
    23  object aim for a long process logic. The users can twist the per-NUMA node
    24  size(Cache.Size) to make minimum allocation by profile.
    25  
    26  example gist:
    27  ```go
    28  package main
    29  
    30  import (
    31  	"github.com/lrita/cache"
    32  )
    33  
    34  type object struct {
    35  	X int
    36  }
    37  
    38  var objcache = cache.Cache{New: func() interface{} { return new(object) }}
    39  
    40  func fnxxxx() {
    41  	obj := objcache.Get().(*object)
    42  	obj.X = 0
    43  	// ... do something for a long time
    44  	objcache.Put(obj)
    45  }
    46  ```
    47  
    48  # BufCache
    49  Assigning a slice of byte to a interface{} will cause a allocation, so we
    50  specialize a implementants from Cache.
    51  
    52  example gist:
    53  ```go
    54  package main
    55  
    56  import (
    57  	"net"
    58  
    59  	"github.com/lrita/cache"
    60  )
    61  
    62  var bufcache = cache.BufCache{New: func() []byte { return make([]byte, 1024) }}
    63  
    64  func fnxxxx(conn net.Conn) {
    65  	buf := bufcache.Get()
    66  	n,err := conn.Read(buf)
    67  	if err != nil {
    68  		panic(err)
    69  	}
    70  	buf = buf[:n]
    71  	// ... do something for a long time
    72  
    73  	bufcache.Put(buf[:cap(buf)])
    74  }
    75  ```