types/views: add BenchmarkSliceIteration

```
goos: darwin
goarch: arm64
pkg: tailscale.com/types/views
BenchmarkSliceIteration/Len-10            340093              3212 ns/op               0 B/op          0 allocs/op
BenchmarkSliceIteration/Cached-Len-10     366727              3211 ns/op               0 B/op          0 allocs/op
BenchmarkSliceIteration/direct-10         361561              3290 ns/op               0 B/op          0 allocs/op
PASS
ok      tailscale.com/types/views       3.662s
```

Signed-off-by: Maisem Ali <maisem@tailscale.com>
pull/5190/head
Maisem Ali 2 years ago committed by Maisem Ali
parent fa2fbaf3aa
commit 51c3d74095

@ -15,6 +15,51 @@ import (
qt "github.com/frankban/quicktest" qt "github.com/frankban/quicktest"
) )
type viewStruct struct {
Int int
Addrs IPPrefixSlice
Strings Slice[string]
AddrsPtr *IPPrefixSlice `json:",omitempty"`
StringsPtr *Slice[string] `json:",omitempty"`
}
func BenchmarkSliceIteration(b *testing.B) {
var data []viewStruct
for i := 0; i < 10000; i++ {
data = append(data, viewStruct{Int: i})
}
b.ResetTimer()
b.Run("Len", func(b *testing.B) {
b.ReportAllocs()
dv := SliceOf(data)
for it := 0; it < b.N; it++ {
sum := 0
for i := 0; i < dv.Len(); i++ {
sum += dv.At(i).Int
}
}
})
b.Run("Cached-Len", func(b *testing.B) {
b.ReportAllocs()
dv := SliceOf(data)
for it := 0; it < b.N; it++ {
sum := 0
for i, n := 0, dv.Len(); i < n; i++ {
sum += dv.At(i).Int
}
}
})
b.Run("direct", func(b *testing.B) {
b.ReportAllocs()
for it := 0; it < b.N; it++ {
sum := 0
for _, d := range data {
sum += d.Int
}
}
})
}
func TestViewsJSON(t *testing.T) { func TestViewsJSON(t *testing.T) {
mustCIDR := func(cidrs ...string) (out []netip.Prefix) { mustCIDR := func(cidrs ...string) (out []netip.Prefix) {
for _, cidr := range cidrs { for _, cidr := range cidrs {
@ -22,12 +67,6 @@ func TestViewsJSON(t *testing.T) {
} }
return return
} }
type viewStruct struct {
Addrs IPPrefixSlice
Strings Slice[string]
AddrsPtr *IPPrefixSlice `json:",omitempty"`
StringsPtr *Slice[string] `json:",omitempty"`
}
ipp := IPPrefixSliceOf(mustCIDR("192.168.0.0/24")) ipp := IPPrefixSliceOf(mustCIDR("192.168.0.0/24"))
ss := SliceOf([]string{"bar"}) ss := SliceOf([]string{"bar"})
tests := []struct { tests := []struct {
@ -38,17 +77,18 @@ func TestViewsJSON(t *testing.T) {
{ {
name: "empty", name: "empty",
in: viewStruct{}, in: viewStruct{},
wantJSON: `{"Addrs":null,"Strings":null}`, wantJSON: `{"Int":0,"Addrs":null,"Strings":null}`,
}, },
{ {
name: "everything", name: "everything",
in: viewStruct{ in: viewStruct{
Int: 1234,
Addrs: ipp, Addrs: ipp,
AddrsPtr: &ipp, AddrsPtr: &ipp,
StringsPtr: &ss, StringsPtr: &ss,
Strings: ss, Strings: ss,
}, },
wantJSON: `{"Addrs":["192.168.0.0/24"],"Strings":["bar"],"AddrsPtr":["192.168.0.0/24"],"StringsPtr":["bar"]}`, wantJSON: `{"Int":1234,"Addrs":["192.168.0.0/24"],"Strings":["bar"],"AddrsPtr":["192.168.0.0/24"],"StringsPtr":["bar"]}`,
}, },
} }

Loading…
Cancel
Save