jmattheis / goverter

Generate type-safe Go converters by simply defining an interface
https://goverter.jmattheis.de/
MIT License
496 stars 46 forks source link

[Questions] Does the generated code need optimization? #53

Closed shuqingzai closed 1 year ago

shuqingzai commented 1 year ago

Have you read the project readme?

Describe your question A clear and concise description of what the question is. Include errors and go source files.

type Tx int

type In struct {
    A Tx
}
type Out struct {
    A Tx
}

// goverter:converter
type Converter interface {
    Convert(in constructor.In) (constructor.Out, error)
    ConvertList(in []constructor.In) ([]constructor.Out, error)
}

result: generated.go

// Code generated by github.com/jmattheis/goverter, DO NOT EDIT.

package generated

import (
    "fmt"
    constructor "xxx/constructor"
)

type ConverterImpl struct{}

func (c *ConverterImpl) Convert(source constructor.In) (constructor.Out, error) {
    var constructorOut constructor.Out
    constructorOut.A = constructor.Tx(source.A)
    return constructorOut, nil
}
func (c *ConverterImpl) ConvertList(source []constructor.In) ([]constructor.Out, error) {
    var constructorOutList []constructor.Out
    if source != nil {
        constructorOutList = make([]constructor.Out, len(source))
        for i := 0; i < len(source); i++ {
            constructorOut, err := c.Convert(source[i])
            if err != nil {
                var errValue []constructor.Out
                return errValue, fmt.Errorf("error setting index %d: %w", i, err)
            }
            constructorOutList[i] = constructorOut
        }
    }
    return constructorOutList, nil
}
  1. The field type is related, they are all Tx, just assign directly? No forced conversion required?
  2. If it is a slice, len(source) is used twice, use the variable to receive, reduce the number of calls?
jmattheis commented 1 year ago
  1. I'd expect the go compiler to just optimize it away. This edge case could be fixed in goverter, but it's probably not necessary. If you can prove that it'll affect performance, I'd be happy to adjust this.
  2. Actually, len(source) is called for every iteration in the for loop. This is kinda a basic use-case so the go compiler should optimize it too. See https://stackoverflow.com/a/26634977/424499