Skip to content
This repository has been archived by the owner on Feb 17, 2024. It is now read-only.

Commit

Permalink
optimize memory allocation of stdio buffers in tests
Browse files Browse the repository at this point in the history
Signed-off-by: Achille Roussel <[email protected]>
  • Loading branch information
achille-roussel committed May 31, 2023
1 parent 53c485d commit 38a4947
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package main_test

import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"

"golang.org/x/exp/maps"
Expand Down Expand Up @@ -78,8 +79,10 @@ func timecraft(t *testing.T, args ...string) (stdout, stderr string, err error)
defer cancel()
}

outbuf := new(strings.Builder)
errbuf := new(strings.Builder)
outbuf := acquireBuffer()
errbuf := acquireBuffer()
defer releaseBuffer(outbuf)
defer releaseBuffer(errbuf)

cmd := exec.CommandContext(ctx, "./timecraft", args...)
cmd.Stdout = outbuf
Expand All @@ -88,3 +91,19 @@ func timecraft(t *testing.T, args ...string) (stdout, stderr string, err error)
err = cmd.Run()
return outbuf.String(), errbuf.String(), err
}

var buffers sync.Pool

func acquireBuffer() *bytes.Buffer {
b, _ := buffers.Get().(*bytes.Buffer)
if b == nil {
b = new(bytes.Buffer)
} else {
b.Reset()
}
return b
}

func releaseBuffer(b *bytes.Buffer) {
buffers.Put(b)
}

0 comments on commit 38a4947

Please sign in to comment.