Skip to content

Commit 8618112

Browse files
committed
os: allocate buffer lazily in Expand
As an example of why this might happen, consider this code from cmd/internal/objfile: // Expand literal "$GOROOT" rewritten by obj.AbsFile() filename = filepath.Clean(os.ExpandEnv(filename)) In this case, filename might not contain "$GOROOT", in which case we can skip the buffer entirely. name old time/op new time/op delta Expand/noop-8 46.7ns ± 1% 12.9ns ± 1% -72.47% (p=0.000 n=9+9) Expand/multiple-8 139ns ± 1% 137ns ± 1% -1.36% (p=0.001 n=10+10) The Expand/multiple improvement is probably noise. This speeds up cmd/objdump detectably, if not much. Using "benchcmd ObjdumpCompile go tool objdump `go tool -n compile`": name old time/op new time/op delta ObjdumpCompile 9.35s ± 2% 9.07s ± 3% -3.00% (p=0.000 n=18+18) Updates #24725 Change-Id: Id31ec6a9b8dfb3c0f1db58fe1f958e11c39e656c Reviewed-on: https://go-review.googlesource.com/106697 Run-TryBot: Josh Bleecher Snyder <josharian@gmail.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
1 parent 3cb067d commit 8618112

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/os/env.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,14 @@ import (
1414
// Expand replaces ${var} or $var in the string based on the mapping function.
1515
// For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).
1616
func Expand(s string, mapping func(string) string) string {
17-
buf := make([]byte, 0, 2*len(s))
17+
var buf []byte
1818
// ${} is all ASCII, so bytes are fine for this operation.
1919
i := 0
2020
for j := 0; j < len(s); j++ {
2121
if s[j] == '$' && j+1 < len(s) {
22+
if buf == nil {
23+
buf = make([]byte, 0, 2*len(s))
24+
}
2225
buf = append(buf, s[i:j]...)
2326
name, w := getShellName(s[j+1:])
2427
// If the name is empty, keep the $.
@@ -31,6 +34,9 @@ func Expand(s string, mapping func(string) string) string {
3134
i = j + 1
3235
}
3336
}
37+
if buf == nil {
38+
return s
39+
}
3440
return string(buf) + s[i:]
3541
}
3642

0 commit comments

Comments
 (0)