git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/validate/arrays_benchmark_test.go (about)

     1  package validate
     2  
     3  // Benchmark testing is produced with randomly filled array of 1 million elements
     4  
     5  import (
     6  	"math/rand"
     7  	"testing"
     8  )
     9  
    10  func randomInt(min, max int) int {
    11  	return min + rand.Intn(max-min)
    12  }
    13  
    14  func randomArray(n int) (res []interface{}) {
    15  	res = make([]interface{}, n)
    16  
    17  	for i := 0; i < n; i++ {
    18  		res[i] = randomInt(-1000, 1000)
    19  	}
    20  
    21  	return
    22  }
    23  
    24  func BenchmarkEach(b *testing.B) {
    25  	data := randomArray(1000000)
    26  	b.ResetTimer()
    27  	for n := 0; n < b.N; n++ {
    28  		acc := 0
    29  		var fn Iterator = func(value interface{}, index int) {
    30  			acc = acc + value.(int)
    31  		}
    32  		Each(data, fn)
    33  	}
    34  }
    35  
    36  func BenchmarkMap(b *testing.B) {
    37  	data := randomArray(1000000)
    38  	b.ResetTimer()
    39  	for n := 0; n < b.N; n++ {
    40  		var fn ResultIterator = func(value interface{}, index int) interface{} {
    41  			return value.(int) * 3
    42  		}
    43  		_ = Map(data, fn)
    44  	}
    45  }
    46  
    47  func BenchmarkFind(b *testing.B) {
    48  	data := randomArray(1000000)
    49  	b.ResetTimer()
    50  	for n := 0; n < b.N; n++ {
    51  		findElement := 96
    52  		var fn1 ConditionIterator = func(value interface{}, index int) bool {
    53  			return value.(int) == findElement
    54  		}
    55  		_ = Find(data, fn1)
    56  	}
    57  }
    58  
    59  func BenchmarkFilter(b *testing.B) {
    60  	data := randomArray(1000000)
    61  	b.ResetTimer()
    62  	for n := 0; n < b.N; n++ {
    63  		var fn ConditionIterator = func(value interface{}, index int) bool {
    64  			return value.(int)%2 == 0
    65  		}
    66  		_ = Filter(data, fn)
    67  	}
    68  }
    69  
    70  func BenchmarkCount(b *testing.B) {
    71  	data := randomArray(1000000)
    72  	b.ResetTimer()
    73  	for n := 0; n < b.N; n++ {
    74  		var fn ConditionIterator = func(value interface{}, index int) bool {
    75  			return value.(int)%2 == 0
    76  		}
    77  		_ = Count(data, fn)
    78  	}
    79  }