Skip to content

Commit f9dd682

Browse files
mrexodialafriks
authored andcommitted
Improve memory usage for Blob.Data() by ~50% (go-gitea#96)
Signed-off-by: Duncan Ogilvie <mr.exodia.tpodt@gmail.com>
1 parent 6196634 commit f9dd682

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

blob.go

+9-4
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,16 @@ type Blob struct {
2222
// Data gets content of blob all at once and wrap it as io.Reader.
2323
// This can be very slow and memory consuming for huge content.
2424
func (b *Blob) Data() (io.Reader, error) {
25-
stdout, err := NewCommand("show", b.ID.String()).RunInDirBytes(b.repo.Path)
26-
if err != nil {
27-
return nil, err
25+
stdout := new(bytes.Buffer)
26+
stderr := new(bytes.Buffer)
27+
28+
// Preallocate memory to save ~50% memory usage on big files.
29+
stdout.Grow(int(b.Size() + 2048))
30+
31+
if err := b.DataPipeline(stdout, stderr); err != nil {
32+
return nil, concatenateError(err, stderr.String())
2833
}
29-
return bytes.NewBuffer(stdout), nil
34+
return stdout, nil
3035
}
3136

3237
// DataPipeline gets content of blob and write the result or error to stdout or stderr

blob_test.go

+3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ var testBlob = &Blob{
1717
repo: &Repository{},
1818
TreeEntry: &TreeEntry{
1919
ID: MustIDFromString("176d8dfe018c850d01851b05fb8a430096247353"),
20+
ptree: &Tree{
21+
repo: &Repository{},
22+
},
2023
},
2124
}
2225

0 commit comments

Comments
 (0)