Skip to content

cmd/compile: evaluate map initializers incrementally #26552

@randall77

Description

@randall77
func g() int
func f() map[int]int {
	return map[int]int{
		1: g(),
		2: g(),
		3: g(),
	}
}

The generated assembly does essentially:

    m = make(map[int]int)
    v1 = g()
    v2 = g()
    v3 = g()
    m[1] = v1
    m[2] = v2
    m[3] = v3

It would be better to evaluate the function g just before we need its result. So instead, do:

    m = make(map[int]int)
    v1 = g()
    m[1] = v1
    v2 = g()
    m[2] = v2
    v3 = g()
    m[3] = v3

It should be safe to do so, as when we're constructing m no one but the current stack frame has a reference to it, so g can't see the difference.

See #26546 for an instance where this matters.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions