Skip to content
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

compiler: no stack allocation for varargs that don't escape #4604

Open
eliasnaur opened this issue Nov 15, 2024 · 1 comment
Open

compiler: no stack allocation for varargs that don't escape #4604

eliasnaur opened this issue Nov 15, 2024 · 1 comment
Labels

Comments

@eliasnaur
Copy link
Contributor

Test:

package main

import "testing"

func TestContentAllocs(t *testing.T) {
	res := testing.Benchmark(func(b *testing.B) {
		for range b.N {
			callVariadicString()
			callVariadicStruct()
		}
	})
	if a := res.AllocsPerOp(); a > 0 {
		t.Errorf("%d allocs, expected 0", a)
	}
}

var sink bool
var sink2 string
var sink3 SomeStruct

type SomeStruct struct {
	v int
}

func callVariadicStruct() {
	variadic(new(SomeStruct))
}

func callVariadicString() {
	str := "hi"
	if sink {
		str = "somethingelse"
	}
	variadic(str)
}

//go:noinline
func variadic(args ...any) {
	for _, a := range args {
		switch a := a.(type) {
		case string:
			sink2 = a
		case *SomeStruct:
			sink3 = *a
		}
	}
}

Tests

$ go test -gcflags=-l      # disable inlining
PASS
ok  	example.com	1.815s
$ tinygo test -opt 2
--- FAIL: TestContentAllocs (2.18s)
    2 allocs, expected 0
FAIL
FAIL	example.com	2.384s
@aykevl
Copy link
Member

aykevl commented Nov 18, 2024

Note that variadic parameters are basically just syntactic sugar in Go. This would be equivalent:

func callVariadicStruct() {
	variadic([]any{new(SomeStruct)})
}

func callVariadicString() {
	str := "hi"
	if sink {
		str = "somethingelse"
	}
	variadic([]any{str})
}

//go:noinline
func variadic(args []any) {
	for _, a := range args {
		switch a := a.(type) {
		case string:
			sink2 = a
		case *SomeStruct:
			sink3 = *a
		}
	}
}

So the issue here seems to be that while the []any slice can be stack allocated, a pointer inside an interface inside a slice can't be. I don't know how the Go compiler manages to avoid allocations here, because it's basically an allocation inside an allocation.

(Also, sidenote, AFAIK the Go compiler also supports //go:noinline).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants