From d1887676d96daf969d886a4ec13cbad4908d51af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Sun, 3 Mar 2019 23:52:00 +0000 Subject: [PATCH] os/exec: less allocs in the common case MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Stdin, Stdout, and Stderr are nil, there are no goroutines to keep track of, so we don't need a channel. And in startProcess, preallocate the right size for sysattr.Files, saving a bit of space and a couple of slice growth allocs. name old time/op new time/op delta ExecHostname-8 419µs ± 0% 417µs ± 1% ~ (p=0.093 n=6+6) name old alloc/op new alloc/op delta ExecHostname-8 6.40kB ± 0% 6.28kB ± 0% -1.86% (p=0.002 n=6+6) name old allocs/op new allocs/op delta ExecHostname-8 34.0 ± 0% 31.0 ± 0% -8.82% (p=0.002 n=6+6) Change-Id: Ic1d617f29e9c6431cdcadc7f9bb992750a6d5f48 Reviewed-on: https://go-review.googlesource.com/c/164801 Run-TryBot: Daniel Martí TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- src/os/exec/exec.go | 13 ++++++++----- src/os/exec_plan9.go | 1 + src/os/exec_posix.go | 1 + 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/os/exec/exec.go b/src/os/exec/exec.go index 30fd64a4b1..424b49cf06 100644 --- a/src/os/exec/exec.go +++ b/src/os/exec/exec.go @@ -404,11 +404,14 @@ func (c *Cmd) Start() error { c.closeDescriptors(c.closeAfterStart) - c.errch = make(chan error, len(c.goroutine)) - for _, fn := range c.goroutine { - go func(fn func() error) { - c.errch <- fn() - }(fn) + // Don't allocate the channel unless there are goroutines to fire. + if len(c.goroutine) > 0 { + c.errch = make(chan error, len(c.goroutine)) + for _, fn := range c.goroutine { + go func(fn func() error) { + c.errch <- fn() + }(fn) + } } if c.ctx != nil { diff --git a/src/os/exec_plan9.go b/src/os/exec_plan9.go index bab16ccad3..b0abf743dd 100644 --- a/src/os/exec_plan9.go +++ b/src/os/exec_plan9.go @@ -27,6 +27,7 @@ func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err e Sys: attr.Sys, } + sysattr.Files = make([]uintptr, 0, len(attr.Files)) for _, f := range attr.Files { sysattr.Files = append(sysattr.Files, f.Fd()) } diff --git a/src/os/exec_posix.go b/src/os/exec_posix.go index 4c8261295c..7b1ef67d1c 100644 --- a/src/os/exec_posix.go +++ b/src/os/exec_posix.go @@ -40,6 +40,7 @@ func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err e if sysattr.Env == nil { sysattr.Env = Environ() } + sysattr.Files = make([]uintptr, 0, len(attr.Files)) for _, f := range attr.Files { sysattr.Files = append(sysattr.Files, f.Fd()) }