Skip to content

Commit

Permalink
shares: use more efficient make([]byte, N) not bytes.Repeat([]byte{0}…
Browse files Browse the repository at this point in the history
…, N)

This change uses Go's memory model guarantees that the zero value memory
shall be zeroed and hence to create a slice of 0 bytes aka padding,
we can simply use make([]byte, N) which is much more efficient than
bytes.Repeat([]byte{0}, N) and the benchmarks show this improvement:

```shell
$ benchstat before.txt after.txt
name               old time/op    new time/op    delta
PaddingVsRepeat-8     674ns ± 1%     538ns ± 0%  -20.22%  (p=0.000 n=9+9)

name               old alloc/op   new alloc/op   delta
PaddingVsRepeat-8    1.31kB ± 0%    0.83kB ± 0%  -36.59%  (p=0.000 n=10+10)

name               old allocs/op  new allocs/op  delta
PaddingVsRepeat-8      12.0 ± 0%      11.0 ± 0%   -8.33%  (p=0.000 n=10+10)
```
  • Loading branch information
odeke-em committed Feb 29, 2024
1 parent 4135f35 commit 3d3d637
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 4 deletions.
3 changes: 1 addition & 2 deletions shares/padding.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package shares

import (
"bytes"
"errors"

"github.com/celestiaorg/go-square/namespace"
Expand All @@ -20,7 +19,7 @@ func NamespacePaddingShare(ns namespace.Namespace, shareVersion uint8) (Share, e
if err := b.WriteSequenceLen(0); err != nil {
return Share{}, err
}
padding := bytes.Repeat([]byte{0}, FirstSparseShareContentSize)
padding := make([]byte, FirstSparseShareContentSize)
b.AddData(padding)

share, err := b.Build()
Expand Down
3 changes: 1 addition & 2 deletions shares/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ func zeroPadIfNecessary(share []byte, width int) (padded []byte, bytesOfPadding
}

missingBytes := width - oldLen
padByte := []byte{0}
padding := bytes.Repeat(padByte, missingBytes)
padding := make([]byte, missingBytes)
share = append(share, padding...)
return share, missingBytes
}
Expand Down

0 comments on commit 3d3d637

Please sign in to comment.