Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created February 1, 2020 13:46
Show Gist options
  • Save ostretsov/7d6840b9d199b3ef9d8491c042e0d874 to your computer and use it in GitHub Desktop.
Save ostretsov/7d6840b9d199b3ef9d8491c042e0d874 to your computer and use it in GitHub Desktop.
Compare perfect hash function performance with `IsKeyword()` method
package main
import (
"go/token"
"testing"
)
func BenchmarkIsKeyword(b *testing.B) {
for n := 0; n < b.N; n++ {
for i := token.BREAK; i < token.VAR; i++ {
tokenStr := i.String()
token.IsKeyword(tokenStr)
}
}
}
func isKeyword(name string) bool {
switch name {
case "break":
fallthrough
case "case":
fallthrough
case "chan":
fallthrough
case "const":
fallthrough
case "continue":
fallthrough
case "default":
fallthrough
case "defer":
fallthrough
case "else":
fallthrough
case "fallthrough":
fallthrough
case "for":
fallthrough
case "func":
fallthrough
case "go":
fallthrough
case "goto":
fallthrough
case "if":
fallthrough
case "import":
fallthrough
case "interface":
fallthrough
case "map":
fallthrough
case "package":
fallthrough
case "range":
fallthrough
case "return":
fallthrough
case "select":
fallthrough
case "struct":
fallthrough
case "switch":
fallthrough
case "type":
fallthrough
case "var":
return true
default:
return false
}
}
func BenchmarkPerfectHashFunction(b *testing.B) {
for n := 0; n < b.N; n++ {
for i := token.BREAK; i < token.VAR; i++ {
tokenStr := i.String()
token.IsKeyword(tokenStr)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment