cmd/gc: don't copy []byte during string concatenation

Consider the following code:

s := "(" + string(byteSlice) + ")"

Currently we allocate a new string during []byte->string conversion,
and pass it to concatstrings. String allocation is unnecessary in
this case, because concatstrings does memorize the strings for later use.
This change uses slicebytetostringtmp to construct temp string directly
from []byte buffer and passes it to concatstrings.

I've found few such cases in std lib:

	s += string(msg[off:off+c]) + "."
	buf.WriteString("Sec-WebSocket-Accept: " + string(c.accept) + "\r\n")
	bw.WriteString("Sec-WebSocket-Key: " + string(nonce) + "\r\n")
	err = xml.Unmarshal([]byte("<Top>"+string(data)+"</Top>"), &logStruct)
	d.err = d.syntaxError("invalid XML name: " + string(b))
	return m, ProtocolError("malformed MIME header line: " + string(kv))

But there are much more in our internal code base.

Change-Id: I42f401f317131237ddd0cb9786b0940213af16fb
Reviewed-on: https://go-review.googlesource.com/3163
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
This commit is contained in:
Dmitry Vyukov 2015-01-22 17:56:12 +03:00
parent a7bb393628
commit 205ae07cd3
3 changed files with 47 additions and 2 deletions

View file

@ -46,6 +46,23 @@ func TestMemStats(t *testing.T) {
}
}
func TestStringConcatenationAllocs(t *testing.T) {
n := testing.AllocsPerRun(1e3, func() {
b := make([]byte, 10)
for i := 0; i < 10; i++ {
b[i] = byte(i) + '0'
}
s := "foo" + string(b)
if want := "foo0123456789"; s != want {
t.Fatalf("want %v, got %v", want, s)
}
})
// Only string concatenation allocates.
if n != 1 {
t.Fatalf("want 1 allocation, got %v", n)
}
}
var mallocSink uintptr
func BenchmarkMalloc8(b *testing.B) {