Why does one string concatenation escape, but the other not?

184 views
Skip to first unread message

tapi...@gmail.com

unread,
Jun 23, 2021, 12:39:17 AM6/23/21
to golang-nuts

package main

import "testing"

var s33 = []byte{32: 'b'}

var a = string(s33)

func main() {
    x := a + a // a + a does not escape
    println(x)
}

func Benchmark_e_33(b *testing.B) {
    var x string
    for i := 0; i < b.N; i++ {
        x = a + a // a + a escapes to heap
    }
    println(x)
}

tapi...@gmail.com

unread,
Jun 23, 2021, 1:19:11 AM6/23/21
to golang-nuts
Is this to avoid stack growing to fast if there are some stack allocations intervening with each other?

jake...@gmail.com

unread,
Jun 23, 2021, 12:00:43 PM6/23/21
to golang-nuts
It does not answer your question, but possibly provides more clues: https://play.golang.org/p/s9Xnpcx8Mys

package main

func main() {
    var a = "b"
    x := a + a // does not escape
    x = a + a  // does not escape
    for i := 0; i < 1; i++ {

        x = a + a  // a + a escapes to heap
        y := a + a // does not escape
        println(y)
        println(x)
    }
}


Only when a variable outside the loop is set inside the loop does it escape. 

On Wednesday, June 23, 2021 at 12:39:17 AM UTC-4 tapi...@gmail.com wrote:

tapi...@gmail.com

unread,
Jun 24, 2021, 4:23:11 AM6/24/21
to golang-nuts
On Wednesday, June 23, 2021 at 12:00:43 PM UTC-4 jake...@gmail.com wrote:
It does not answer your question, but possibly provides more clues: https://play.golang.org/p/s9Xnpcx8Mys

package main

func main() {
    var a = "b"
    x := a + a // does not escape
    x = a + a  // does not escape
    for i := 0; i < 1; i++ {

        x = a + a  // a + a escapes to heap
        y := a + a // does not escape
        println(y)
        println(x)
    }
}


Only when a variable outside the loop is set inside the loop does it escape. 

Yes, testing is not relevant here. It is the loop make effects here.

tapi...@gmail.com

unread,
Jun 24, 2021, 10:50:31 PM6/24/21
to golang-nuts
Now, I think the escape analysis message should be "a + a does not escapes",
which accurate meaning is "the header part of a + a does not escape".
It is impossible for the compiler to determine whether or notthe underlying part of "a + a" will escape to heap.

On Wednesday, June 23, 2021 at 12:00:43 PM UTC-4 jake...@gmail.com wrote:

tapi...@gmail.com

unread,
Jun 24, 2021, 10:51:11 PM6/24/21
to golang-nuts
Reply all
Reply to author
Forward
0 new messages