zarldev / goenums

Type Safe Enum generator for Go
MIT License
222 stars 10 forks source link

Use an array instead of map for converting ints into strings #1

Closed Verseth closed 7 months ago

Verseth commented 7 months ago

I think an array would be more appropriate for mapping ints to strings, since all values are guaranteed to be incremental.

Lookup in an array should be faster since go doesn't have to calculate the hash from the key, it just uses the integer directly as the index.

So instead of code like this:

type status int

const (
    unknown status = iota
    failed
    passed
    skipped
    scheduled
    running
)

var (
    strStatusMap = map[status]string{
        failed:    "FAILED",
        passed:    "PASSED",
        skipped:   "SKIPPED",
        scheduled: "SCHEDULED",
        running:   "RUNNING",
    }

    typeStatusMap = map[string]status{
        "FAILED":    failed,
        "PASSED":    passed,
        "SKIPPED":   skipped,
        "SCHEDULED": scheduled,
        "RUNNING":   running,
    }
)

You could generate this:

type status int

const (
    unknown status = iota
    failed
    passed
    skipped
    scheduled
    running
)

var (
    strStatusMap = [...]string{
        failed:    "FAILED",
        passed:    "PASSED",
        skipped:   "SKIPPED",
        scheduled: "SCHEDULED",
        running:   "RUNNING",
    }

    typeStatusMap = map[string]status{
        "FAILED":    failed,
        "PASSED":    passed,
        "SKIPPED":   skipped,
        "SCHEDULED": scheduled,
        "RUNNING":   running,
    }
)
zarldev commented 7 months ago

Yeah this will also impact the IsValid function as that is used for the look up. That can be mitigated though by doing greater than less than checks I suppose.

zarldev commented 7 months ago

https://github.com/zarldev/goenums/blob/3c41a0f3c0834d86acf6c013d5790fbe3e205c7b/pkg/generator/template/enum.tmpl#L23

Updated.