github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bench/iterate/example_test.go (about)

     1  // Type your code here, or load an example.
     2  // Your function name should start with a capital letter.
     3  package main
     4  
     5  import (
     6  	"strconv"
     7  	"testing"
     8  	"time"
     9  )
    10  
    11  type Private struct {
    12  	Name     string
    13  	Created  int64
    14  	Modified int64
    15  	User     []KeyValue
    16  }
    17  
    18  type KeyValue struct{ Key, Value string }
    19  
    20  func convert(values []KeyValue) map[string]string {
    21  	if len(values) == 0 {
    22  		return nil
    23  	}
    24  	xs := map[string]string{}
    25  	for _, kv := range values {
    26  		xs[kv.Key] = kv.Value
    27  	}
    28  	return xs
    29  }
    30  
    31  type Object struct {
    32  	Name     string
    33  	Created  time.Time
    34  	Modified time.Time
    35  	User     map[string]string
    36  }
    37  type List struct {
    38  	Prefix string
    39  	Items  []Private
    40  	Index  int
    41  }
    42  
    43  func (p *List) Next() bool {
    44  	p.Index++
    45  	return p.Index <= len(p.Items)
    46  }
    47  
    48  func (p *List) Item() Object {
    49  	item := &p.Items[p.Index-1]
    50  	return Object{
    51  		Name:     p.Prefix + item.Name,
    52  		Created:  time.Unix(item.Created, 0),
    53  		Modified: time.Unix(item.Modified, 0),
    54  		User:     convert(item.User),
    55  	}
    56  }
    57  
    58  func (p *List) ItemPtr() *Object {
    59  	item := &p.Items[p.Index-1]
    60  	return &Object{
    61  		Name:     p.Prefix + item.Name,
    62  		Created:  time.Unix(item.Created, 0),
    63  		Modified: time.Unix(item.Modified, 0),
    64  		User:     convert(item.User),
    65  	}
    66  }
    67  
    68  var data = func() []Private {
    69  	var xs []Private
    70  	for i := 0; i < 100; i++ {
    71  		xs = append(xs, Private{
    72  			Name:     strconv.Itoa(i),
    73  			Created:  int64(i)*1000 + time.Now().Unix(),
    74  			Modified: int64(i)*1000 + time.Now().Unix(),
    75  			User:     []KeyValue{{"A", "B"}},
    76  		})
    77  	}
    78  	return xs
    79  }()
    80  
    81  func BenchmarkStruct(b *testing.B) {
    82  	for i := 0; i < b.N; i++ {
    83  		list := List{
    84  			Prefix: "xyz/",
    85  			Index:  0,
    86  			Items:  data,
    87  		}
    88  		var size int
    89  		for list.Next() {
    90  			size += len(list.Item().Name)
    91  		}
    92  		_ = size
    93  	}
    94  }
    95  
    96  func BenchmarkPtr(b *testing.B) {
    97  	for i := 0; i < b.N; i++ {
    98  		list := List{
    99  			Prefix: "xyz/",
   100  			Index:  0,
   101  			Items:  data,
   102  		}
   103  		var size int
   104  		for list.Next() {
   105  			size += len(list.ItemPtr().Name)
   106  		}
   107  		_ = size
   108  	}
   109  }