Skip to content

cmd/compile: don't allocate when putting constant strings in an interface #18704

@josharian

Description

@josharian

fmt.Println("abc") allocates when it converts "abc" into an interface. It should not.

When the compiler sees a constant string being converted into an interface (usually at a call site?), it could create a static interface value to use, rather than allocating it at runtime.

That is, do the following conversion automatically:

var abc interface{} = "ABC"

func BenchmarkPrintln(b *testing.B) {
	b.Run("regular", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			fmt.Fprintln(ioutil.Discard, "ABC")
		}
	})
	b.Run("prealloc", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			fmt.Fprintln(ioutil.Discard, abc)
		}
	})
}

This might not be as bad for binary size as it initially appears; it might even be an improvement. The cost of the runtime conversion call is probably about as large as the two additional words of static data plus symbol overhead. (And that symbol overhead could be removed if necessary, as we did for strings.)

See also #17725 and the golang-dev thread about logging that insired this.

cc @randall77 @mdempsky @bradfitz

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions