github.com/duomi520/utils@v0.0.0-20240430123446-e03a4cddd6ec/cache_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  )
     7  
     8  func TestIdempotentCache(t *testing.T) {
     9  	fn := func(d []byte) any {
    10  		return len(d)
    11  	}
    12  	ic := &IdempotentCache[[]byte]{}
    13  	ic.Init(12, 0x0102030405060708, fn)
    14  	key1 := []byte("127.0.0.1")
    15  	key2 := []byte("192.168.0.1")
    16  	t.Log(ic.Get(key1))
    17  	t.Log(ic.Get(key2))
    18  	t.Log(ic.Get(key1))
    19  }
    20  func BenchmarkSyncMap(b *testing.B) {
    21  	var m sync.Map
    22  	m.Store("127.0.0.1", true)
    23  	for i := 0; i < b.N; i++ {
    24  		m.Load("127.0.0.1")
    25  	}
    26  }
    27  
    28  func BenchmarkIdempotentCacheGet(b *testing.B) {
    29  	fn := func(s string) any {
    30  		var compute int
    31  		for i := 0; i < 100; i++ {
    32  			compute = len(s) ^ i
    33  		}
    34  		return compute
    35  	}
    36  	ic := &IdempotentCache[string]{}
    37  	ic.Init(5, 0x0102030405060708, fn)
    38  	for i := 0; i < b.N; i++ {
    39  		ic.Get("127.0.0.1")
    40  	}
    41  }