Skip to content

Commit 28f4a5e

Browse files
committed
Benchmark existing ways to check for IDENTITY CIDs
Add benchmarks that compare two ways of checking for `multihash.IDENTITY` code: 1. `Cid.Prefix().MhType` 2. Decode of `Cid.Hash()` This benchmark illustrates that using Cid.Prefix is more efficient than `multihash.Decode`. Users wishing to perform such a check should use `Cid.Prefix`. Consider that `Cid.Prefix` is already efficient enough and introducing a dedicated API for performing this check will likely result in small gains. Relates to #133
1 parent 5640b01 commit 28f4a5e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

benchmark_test.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package cid_test
2+
3+
import (
4+
"math/rand"
5+
"testing"
6+
7+
"github.com/ipfs/go-cid"
8+
"github.com/multiformats/go-multihash"
9+
)
10+
11+
// BenchmarkIdentityCheck benchmarks two ways of checking whether a CIDv1 has multihash.IDENTITY
12+
// code:
13+
// 1. Cid.Prefix(), and
14+
// 2. decoding the Cid.Hash().
15+
//
16+
// This benchmark illustrates that using Cid.Prefix is more efficient than multihash.Decode.
17+
// Users wishing to perform such a check should use Cid.Prefix.
18+
//
19+
// Consider that `Cid.Prefix` is already efficient enough and introducing a dedicated API for
20+
// performing this check will likely result in small gains.
21+
func BenchmarkIdentityCheck(b *testing.B) {
22+
rng := rand.New(rand.NewSource(1413))
23+
24+
data := make([]byte, rng.Intn(100)+1024)
25+
if _, err := rng.Read(data); err != nil {
26+
b.Fatal(err)
27+
}
28+
mh, err := multihash.Sum(data, multihash.IDENTITY, -1)
29+
if err != nil {
30+
b.Fatal(err)
31+
}
32+
cv1 := cid.NewCidV1(cid.Raw, mh)
33+
34+
b.SetBytes(int64(cv1.ByteLen()))
35+
b.ReportAllocs()
36+
b.ResetTimer()
37+
38+
b.Run("Prefix", func(b *testing.B) {
39+
b.RunParallel(func(pb *testing.PB) {
40+
for pb.Next() {
41+
if cv1.Prefix().MhType != multihash.IDENTITY {
42+
b.Fatal("expected IDENTITY CID")
43+
}
44+
}
45+
})
46+
})
47+
48+
b.Run("MultihashDecode", func(b *testing.B) {
49+
b.RunParallel(func(pb *testing.PB) {
50+
for pb.Next() {
51+
dmh, err := multihash.Decode(cv1.Hash())
52+
if err != nil {
53+
b.Fatal(err)
54+
}
55+
if dmh.Code != multihash.IDENTITY {
56+
b.Fatal("expected IDENTITY CID")
57+
}
58+
}
59+
})
60+
})
61+
}

0 commit comments

Comments
 (0)