diff --git a/benchmark_test.go b/benchmark_test.go new file mode 100644 index 0000000..a60f8b1 --- /dev/null +++ b/benchmark_test.go @@ -0,0 +1,62 @@ +package cid_test + +import ( + "github.com/ipfs/go-cid" + "github.com/multiformats/go-multihash" + "math/rand" + "testing" +) + +// BenchmarkIdentityCheck benchmarks checking whether a CIDv1 has multihash.IDENTITY +// code via two methods: 1) Cid.Prefix() and 2) decoding the Cid.Hash(). +func BenchmarkIdentityCheck(b *testing.B) { + rng := rand.New(rand.NewSource(1413)) + cv1 := generateCidV1(b, rng, multihash.IDENTITY) + + b.SetBytes(int64(cv1.ByteLen())) + b.ReportAllocs() + b.ResetTimer() + + b.Run("Prefix", func(bb *testing.B) { + bb.RunParallel(func(pb *testing.PB) { + for pb.Next() { + if cv1.Prefix().MhType != multihash.IDENTITY { + b.Fatal("expected IDENTITY CID") + } + } + }) + }) + + b.Run("MultihashDecode", func(bb *testing.B) { + bb.RunParallel(func(pb *testing.PB) { + for pb.Next() { + dmh, err := multihash.Decode(cv1.Hash()) + if err != nil { + b.Fatal(err) + } + if dmh.Code != multihash.IDENTITY { + b.Fatal("expected IDENTITY CID") + } + } + }) + }) +} + +func generateMultihash(b *testing.B, rng *rand.Rand, mhCode uint64) multihash.Multihash { + // Generate random data to hash. + data := make([]byte, rng.Intn(100)+1024) + if _, err := rng.Read(data); err != nil { + b.Fatal(err) + } + // Generate multihash from data. + mh, err := multihash.Sum(data, mhCode, -1) + if err != nil { + b.Fatal(err) + } + return mh +} + +func generateCidV1(b *testing.B, rng *rand.Rand, mhCode uint64) cid.Cid { + mh := generateMultihash(b, rng, mhCode) + return cid.NewCidV1(cid.Raw, mh) +}