From 419909d44b6cae26c04199b1151713d243050550 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Mon, 11 Mar 2019 16:12:48 +0000 Subject: [PATCH] syntax: reuse a single tabwriter in a printer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mostly allows saving allocations. name old time/op new time/op delta Print-8 11.2µs ± 1% 10.3µs ± 1% -8.21% (p=0.002 n=6+6) name old alloc/op new alloc/op delta Print-8 1.06kB ± 0% 0.34kB ± 0% -67.42% (p=0.002 n=6+6) name old allocs/op new allocs/op delta Print-8 24.0 ± 0% 10.0 ± 0% -58.33% (p=0.002 n=6+6) --- syntax/printer.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/syntax/printer.go b/syntax/printer.go index ea7cb2deb..3628eb0f0 100644 --- a/syntax/printer.go +++ b/syntax/printer.go @@ -55,6 +55,7 @@ func NewPrinter(options ...func(*Printer)) *Printer { p := &Printer{ bufWriter: bufio.NewWriter(nil), tabsPrinter: new(Printer), + tabWriter: new(tabwriter.Writer), } for _, opt := range options { opt(p) @@ -82,7 +83,8 @@ func (p *Printer) Print(w io.Writer, node Node) error { // indenting with spaces tabwidth = int(p.indentSpaces) } - w = tabwriter.NewWriter(w, 0, tabwidth, 1, ' ', twmode) + p.tabWriter.Init(w, 0, tabwidth, 1, ' ', twmode) + w = p.tabWriter p.bufWriter.Reset(w) switch x := node.(type) { @@ -164,6 +166,7 @@ func (c *colCounter) Reset(w io.Writer) { // program. type Printer struct { bufWriter + tabWriter *tabwriter.Writer cols colCounter indentSpaces uint