github.com/tanqiangyes/govalidator@v0.0.5/arrays_benchmark_test.go (about)

     1  package govalidator
     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 []int) {
    15  	res = make([]int, 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  		var fn Iterator[int] = func(value int, index int) {
    29  			value = value + index
    30  		}
    31  		Each(data, fn)
    32  	}
    33  }
    34  
    35  func BenchmarkReduce(b *testing.B) {
    36  	data := randomArray(1000000)
    37  	b.ResetTimer()
    38  	for n := 0; n < b.N; n++ {
    39  		var fn ReduceIterator[int] = func(init int, val int) int {
    40  			return init + val
    41  		}
    42  		Reduce(data, fn, 0)
    43  	}
    44  }
    45  
    46  func BenchmarkMap(b *testing.B) {
    47  	data := randomArray(1000000)
    48  	b.ResetTimer()
    49  	for n := 0; n < b.N; n++ {
    50  		var fn ResultIterator[int] = func(value int, index int) int {
    51  			return value * 3
    52  		}
    53  		_ = Map(data, fn)
    54  	}
    55  }
    56  
    57  func BenchmarkFind(b *testing.B) {
    58  	data := randomArray(1000000)
    59  	b.ResetTimer()
    60  	for n := 0; n < b.N; n++ {
    61  		findElement := 96
    62  		var fn1 ConditionIterator[int] = func(value int, index int) bool {
    63  			return value == findElement
    64  		}
    65  		_ = Find(data, fn1)
    66  	}
    67  }
    68  
    69  func BenchmarkFilter(b *testing.B) {
    70  	data := randomArray(1000000)
    71  	b.ResetTimer()
    72  	for n := 0; n < b.N; n++ {
    73  		var fn ConditionIterator[int] = func(value int, index int) bool {
    74  			return value%2 == 0
    75  		}
    76  		_ = Filter(data, fn)
    77  	}
    78  }
    79  
    80  func BenchmarkCount(b *testing.B) {
    81  	data := randomArray(1000000)
    82  	b.ResetTimer()
    83  	for n := 0; n < b.N; n++ {
    84  		var fn ConditionIterator[int] = func(value int, index int) bool {
    85  			return value%2 == 0
    86  		}
    87  		_ = Count(data, fn)
    88  	}
    89  }