why would slice = slice[1:] allocate

152 views
Skip to first unread message

Jason E. Aten

unread,
Feb 29, 2020, 6:53:18 PM2/29/20
to golang-nuts
Profiling suggests that reslicing to remove the first element of a slice is doing alot of allocation; for instance in mycode() below.
This is surprising to me.... How could this be? is there anything I can do about it?

e.g.

type A struct{
   B string
}

func mycode(slice []A) {
  slice = slice[1:]
}
Message has been deleted

Jason E. Aten

unread,
Mar 1, 2020, 8:56:13 AM3/1/20
to so.pe...@gmail.com, golang-nuts
escape analysis is eliminating the allocation in the simplification. in reality the slice is stored in a persistent struct.

On Sun, Mar 1, 2020 at 8:50 AM <so.pe...@gmail.com> wrote:
Jason,

Your example does not appear to support your claim.

A benchmark:

package main

import (
    "strconv"
    "testing"
)


type A struct {
    B string
}

func mycode(slice []A) {
    slice = slice[1:]
}

func BenchmarkMycode(b *testing.B) {
    a := make([]A, 256)
    for i := range a {
        a[i].B = "B: " + strconv.Itoa(i*cap(a))
    }
    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        mycode(a)
    }
}

Output:

$ go version
go version go1.14 linux/amd64
$ go test mycode_test.go -bench=. -benchmem
BenchmarkMycode-4   1000000000   0.290 ns/op   0 B/op  0 allocs/op

Peter

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/gMF1XdTTlWo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/efc1c5ba-34d0-476f-be3e-7f0c9b84d816%40googlegroups.com.

Ian Lance Taylor

unread,
Mar 1, 2020, 10:37:20 AM3/1/20
to Jason E. Aten, so.pe...@gmail.com, golang-nuts
On Sun, Mar 1, 2020 at 5:56 AM Jason E. Aten <j.e....@gmail.com> wrote:
>
> escape analysis is eliminating the allocation in the simplification. in reality the slice is stored in a persistent struct.

Can you show us a complete example program? It's possible that the
allocation is getting attributed to the wrong line, or that the
expected line has been eliminated by the compiler. Thanks.

Ian
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAPNEFAaaV3RWRs-KZmK-D%2BuTzUB8geUkm-Pca20pOFKv0w9zZA%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages