compiler: optimize new empty struct creation with PACKSTRUCT

This commit is contained in:
Roman Khimov 2021-11-12 16:35:30 +03:00
parent 909ea477f4
commit a8befeea33
2 changed files with 13 additions and 6 deletions

View file

@ -324,14 +324,11 @@ func (c *codegen) emitDefault(t types.Type) {
}
case *types.Struct:
num := t.NumFields()
emit.Int(c.prog.BinWriter, int64(num))
emit.Opcodes(c.prog.BinWriter, opcode.NEWSTRUCT)
for i := 0; i < num; i++ {
emit.Opcodes(c.prog.BinWriter, opcode.DUP)
emit.Int(c.prog.BinWriter, int64(i))
for i := num - 1; i >= 0; i-- {
c.emitDefault(t.Field(i).Type())
emit.Opcodes(c.prog.BinWriter, opcode.SETITEM)
}
emit.Int(c.prog.BinWriter, int64(num))
emit.Opcodes(c.prog.BinWriter, opcode.PACKSTRUCT)
default:
emit.Opcodes(c.prog.BinWriter, opcode.PUSHNULL)
}

View file

@ -394,6 +394,16 @@ var structTestCases = []testCase{
}`,
big.NewInt(11),
},
{
"lengthy struct default value",
`package foo
type S struct { x int; y []byte; z bool }
func Main() int {
var s S
return s.x
}`,
big.NewInt(0),
},
{
"nested selectors (complex write)",
`package foo