Debian Codegraph @

_rsrch/cidiface/cidBoxingBench_test.go

raw
1 package cid
2
3 import (
4 "testing"
5 )
6
7 // BenchmarkCidMap_CidStr estimates how fast it is to insert primitives into a map
8 // keyed by CidStr (concretely).
9 //
10 // We do 100 insertions per benchmark run to make sure the map initialization
11 // doesn't dominate the results.
12 //
13 // Sample results on linux amd64 go1.11beta:
14 //
15 // BenchmarkCidMap_CidStr-8 100000 16317 ns/op
16 // BenchmarkCidMap_CidIface-8 100000 20516 ns/op
17 //
18 // With benchmem on:
19 //
20 // BenchmarkCidMap_CidStr-8 100000 15579 ns/op 11223 B/op 207 allocs/op
21 // BenchmarkCidMap_CidIface-8 100000 19500 ns/op 12824 B/op 307 allocs/op
22 // BenchmarkCidMap_StrPlusHax-8 200000 10451 ns/op 7589 B/op 202 allocs/op
23 //
24 // We can see here that the impact of interface boxing is significant:
25 // it increases the time taken to do the inserts to 133%, largely because
26 // the implied `runtime.convT2E` calls cause another malloc each.
27 //
28 // There are also significant allocations in both cases because
29 // A) we cannot create a multihash without allocations since they are []byte;
30 // B) the map has to be grown several times;
31 // C) something I haven't quite put my finger on yet.
32 // Ideally we'd drive those down further as well.
33 //
34 // Pre-allocating the map reduces allocs by a very small percentage by *count*,
35 // but reduces the time taken by 66% overall (presumably because when a map
36 // re-arranges itself, it involves more or less an O(n) copy of the content
37 // in addition to the alloc itself). This isn't topical to the question of
38 // whether or not interfaces are a good idea; just for contextualizing.
39 func BenchmarkCidMap_CidStr(b *testing.B) {
40 for i := 0; i < b.N; i++ {
41 mp := map[CidStr]int{}
42 for x := 0; x < 100; x++ {
43 mp[NewCidStr(0, uint64(x), []byte{})] = x
44 }
45 }
46 }
47
48 // BenchmarkCidMap_CidIface is in the family of BenchmarkCidMap_CidStr:
49 // it is identical except the map key type is declared as an interface
50 // (which forces all insertions to be boxed, changing performance).
51 func BenchmarkCidMap_CidIface(b *testing.B) {
52 for i := 0; i < b.N; i++ {
53 mp := map[Cid]int{}
54 for x := 0; x < 100; x++ {
55 mp[NewCidStr(0, uint64(x), []byte{})] = x
56 }
57 }
58 }
59
60 // BenchmarkCidMap_CidStrAvoidMapGrowth is in the family of BenchmarkCidMap_CidStr:
61 // it is identical except the map is created with a size hint that removes
62 // some allocations (5, in practice, apparently).
63 func BenchmarkCidMap_CidStrAvoidMapGrowth(b *testing.B) {
64 for i := 0; i < b.N; i++ {
65 mp := make(map[CidStr]int, 100)
66 for x := 0; x < 100; x++ {
67 mp[NewCidStr(0, uint64(x), []byte{})] = x
68 }
69 }
70 }