github.com/rajeev159/opa@v0.45.0/topdown/cache_bench_test.go (about)

     1  // Copyright 2019 The OPA Authors.  All rights reserved.
     2  // Use of this source code is governed by an Apache2
     3  // license that can be found in the LICENSE file.
     4  
     5  package topdown
     6  
     7  import (
     8  	"fmt"
     9  	"testing"
    10  
    11  	"github.com/open-policy-agent/opa/ast"
    12  )
    13  
    14  func BenchmarkVirtualCache(b *testing.B) {
    15  
    16  	n := 10
    17  	max := n * n * n
    18  
    19  	keys := make([]ast.Ref, 0, max)
    20  	values := make([]*ast.Term, 0, max)
    21  
    22  	for i := 0; i < n; i++ {
    23  		k1 := ast.StringTerm(fmt.Sprintf("aaaa%v", i))
    24  		for j := 0; j < n; j++ {
    25  			k2 := ast.StringTerm(fmt.Sprintf("bbbb%v", j))
    26  			for k := 0; k < n; k++ {
    27  				k3 := ast.StringTerm(fmt.Sprintf("cccc%v", k))
    28  				key := ast.Ref{ast.DefaultRootDocument, k1, k2, k3}
    29  				value := ast.ArrayTerm(k1, k2, k3)
    30  				keys = append(keys, key)
    31  				values = append(values, value)
    32  			}
    33  		}
    34  	}
    35  
    36  	cache := newVirtualCache()
    37  	b.ResetTimer()
    38  
    39  	for i := 0; i < b.N; i++ {
    40  		idx := i % max
    41  		cache.Put(keys[idx], values[idx])
    42  		result := cache.Get(keys[idx])
    43  		if !result.Equal(values[idx]) {
    44  			b.Fatal("expected equal")
    45  		}
    46  	}
    47  
    48  }