Skip to content

Commit 2796254

Browse files
pkg/cache: use a shared buffer to limit allocations
Previously, new buffers were allocated on each file we read in, which was unnecessary and wasteful. Signed-off-by: Steve Kuznetsov <[email protected]>
1 parent bca2bfb commit 2796254

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

pkg/cache/json.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -165,13 +165,14 @@ func (q *JSON) existingDigest() (string, error) {
165165
}
166166

167167
func (q *JSON) computeDigest(fbcFsys fs.FS) (string, error) {
168+
buf := make([]byte, 32*1024)
168169
computedHasher := fnv.New64a()
169-
if err := fsToTar(computedHasher, fbcFsys); err != nil {
170+
if err := fsToTar(computedHasher, fbcFsys, buf); err != nil {
170171
return "", err
171172
}
172173

173174
if cacheFS, err := fs.Sub(os.DirFS(q.baseDir), jsonDir); err == nil {
174-
if err := fsToTar(computedHasher, cacheFS); err != nil && !errors.Is(err, os.ErrNotExist) {
175+
if err := fsToTar(computedHasher, cacheFS, buf); err != nil && !errors.Is(err, os.ErrNotExist) {
175176
return "", fmt.Errorf("compute hash: %v", err)
176177
}
177178
}

pkg/cache/tar.go

+5-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import (
1313
// This function unsets user and group information in the tar archive so that readers
1414
// of archives produced by this function do not need to account for differences in
1515
// permissions between source and destination filesystems.
16-
func fsToTar(w io.Writer, fsys fs.FS) error {
16+
func fsToTar(w io.Writer, fsys fs.FS, buf []byte) error {
17+
if buf == nil || len(buf) == 0 {
18+
buf = make([]byte, 32*1024)
19+
}
1720
tw := tar.NewWriter(w)
1821
if err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
1922
if err != nil {
@@ -52,7 +55,7 @@ func fsToTar(w io.Writer, fsys fs.FS) error {
5255
return fmt.Errorf("open file %q: %v", path, err)
5356
}
5457
defer f.Close()
55-
if _, err := io.Copy(tw, f); err != nil {
58+
if _, err := io.CopyBuffer(tw, f, buf); err != nil {
5659
return fmt.Errorf("write tar data for %q: %v", path, err)
5760
}
5861
return nil

0 commit comments

Comments
 (0)