New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/compile: eliminate memory allocation for non-int n in slice extension idiom #29785

Open
valyala opened this Issue Jan 17, 2019 · 3 comments

Comments

Projects
None yet
5 participants
@valyala
Copy link
Contributor

valyala commented Jan 17, 2019

The slice extension idiom from #21266 doesn't work in go tip for non-int n in append(a, make([]T, n)...):

func BenchmarkExtendInt(b *testing.B) {
        var buf []byte
        b.ReportAllocs()
        n := int(12345)
        for i := 0; i < b.N; i++ {
                buf = append(buf[:0], make([]byte, n)...)
        }
}

func BenchmarkExtendUint64(b *testing.B) {
        var buf []byte
        b.ReportAllocs()
        n := uint64(12345)
        for i := 0; i < b.N; i++ {
                buf = append(buf[:0], make([]byte, n)...)
        }
}

Benchmark results:

BenchmarkExtendInt-4      	10000000	       145 ns/op	       0 B/op	       0 allocs/op
BenchmarkExtendUint64-4   	 1000000	      1576 ns/op	   13568 B/op	       1 allocs/op

As you can see, if n has a type other than int, go doesn't remove the allocation.

@valyala valyala changed the title Eliminate memory allocation for non-int n in slice extension idiom cmd/compile: eliminate memory allocation for non-int n in slice extension idiom Jan 17, 2019

@mvdan

This comment has been minimized.

Copy link
Member

mvdan commented Jan 17, 2019

I'm curious - what happens with other integer types like int16 or int64?

@josharian

This comment has been minimized.

Copy link
Contributor

josharian commented Jan 17, 2019

@martisch

This comment has been minimized.

Copy link
Member

martisch commented Jan 17, 2019

This was a known limitation when writing the compiler optimization and there is a todo in the walk.go code to support more types. Adding all types which values fit in an int shouldnt be hard. For types exceeding the value range of int we need additional runtime checks. E.g. if uint64 seems worth supporting even if only for consistency we can add an extra check to throw the same panic as eg makeslice64 does. I have a look at it once the tree opens for go1.13.

@agnivade agnivade added this to the Go1.13 milestone Jan 17, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment