Skip to content

Instantly share code, notes, and snippets.

@chrisvdg
Last active August 23, 2017 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvdg/0da46534fc1c377b351f6ab5880fed8c to your computer and use it in GitHub Desktop.
Save chrisvdg/0da46534fc1c377b351f6ab5880fed8c to your computer and use it in GitHub Desktop.
enum comparison
package main
import (
"fmt"
"time"
)
const (
loops = int(1000)
)
func main() {
stringEnumCases := []StringEnum{
StringEnumKey1,
StringEnumKey2,
StringEnumKey3,
StringEnumKey4,
}
start1 := time.Now()
for i := 0; i < loops; i++ {
for _, se := range stringEnumCases {
se.Validate()
_ = se.String()
_ = se.String()
_ = se.String()
_ = se.String()
_ = se.String()
_ = se.String()
}
}
elapsed := time.Since(start1)
fmt.Printf("string enum took %s\n", elapsed)
intEnumCases := []UINTEnum{
UINTEnumKey1,
UINTEnumKey2,
UINTEnumKey3,
UINTEnumKey4,
}
start2 := time.Now()
for i := 0; i < loops; i++ {
for _, se := range intEnumCases {
se.Validate()
_ = se.String()
_ = se.String()
_ = se.String()
_ = se.String()
_ = se.String()
_ = se.String()
}
}
elapsed = time.Since(start2)
fmt.Printf("uint enum took %s\n", elapsed)
}
/* results (Intel i5-3230M CPU @ 2.60GHz × 4):
string enum took 24.926µs
uint enum took 29.668µs
with only 1 string call:
string enum took 23.814µs
uint enum took 13.169µs
*/
type StringEnum string
// StringEnum options
const (
StringEnumKey1 = StringEnum("vdisk.iops.read")
StringEnumKey2 = StringEnum("vdisk.iops.write")
StringEnumKey3 = StringEnum("vdisk.throughput.read")
StringEnumKey4 = StringEnum("vdisk.throughput.write")
)
// Validate validates a StringEnum
func (se StringEnum) Validate() error {
switch se {
case StringEnumKey1, StringEnumKey2, StringEnumKey3, StringEnumKey4:
return nil
default:
return fmt.Errorf("invalid thingy")
}
}
func (se StringEnum) String() string {
return string(se)
}
type UINTEnum uint8
// UINTEnum options
const (
UINTEnumKey1 = iota
UINTEnumKey2
UINTEnumKey3
UINTEnumKey4
)
// UINTEnum string representations
const (
UINTEnumKey1Str = "vdisk.iops.read"
UINTEnumKey2Str = "vdisk.iops.write"
UINTEnumKey3Str = "vdisk.throughput.read"
UINTEnumKey4Str = "vdisk.throughput.write"
)
func (sk UINTEnum) String() string {
switch sk {
case UINTEnumKey1:
return UINTEnumKey1Str
case UINTEnumKey2:
return UINTEnumKey2Str
case UINTEnumKey3:
return UINTEnumKey3Str
case UINTEnumKey4:
return UINTEnumKey4Str
default:
return ""
}
}
// Validate validates a UINTEnum
func (sk UINTEnum) Validate() error {
switch sk {
case UINTEnumKey1, UINTEnumKey2, UINTEnumKey3, UINTEnumKey4:
return nil
default:
return fmt.Errorf("invalid thingy")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment