Browse Source

Improve performance of LookupCommandInfo

Gary Burd 10 năm trước cách đây
mục cha
commit
27a6a7d7c7
2 tập tin đã thay đổi với 36 bổ sung0 xóa
  1. 9 0
      internal/commandinfo.go
  2. 27 0
      internal/commandinfo_test.go

+ 9 - 0
internal/commandinfo.go

@@ -40,6 +40,15 @@ var commandInfos = map[string]CommandInfo{
 	"MONITOR":    {Set: MonitorState},
 }
 
+func init() {
+	for n, ci := range commandInfos {
+		commandInfos[strings.ToLower(n)] = ci
+	}
+}
+
 func LookupCommandInfo(commandName string) CommandInfo {
+	if ci, ok := commandInfos[commandName]; ok {
+		return ci
+	}
 	return commandInfos[strings.ToUpper(commandName)]
 }

+ 27 - 0
internal/commandinfo_test.go

@@ -0,0 +1,27 @@
+package internal
+
+import "testing"
+
+func TestLookupCommandInfo(t *testing.T) {
+	for _, n := range []string{"watch", "WATCH", "wAtch"} {
+		if LookupCommandInfo(n) == (CommandInfo{}) {
+			t.Errorf("LookupCommandInfo(%q) = CommandInfo{}, expected non-zero value", n)
+		}
+	}
+}
+
+func benchmarkLookupCommandInfo(b *testing.B, names ...string) {
+	for i := 0; i < b.N; i++ {
+		for _, c := range names {
+			LookupCommandInfo(c)
+		}
+	}
+}
+
+func BenchmarkLookupCommandInfoCorrectCase(b *testing.B) {
+	benchmarkLookupCommandInfo(b, "watch", "WATCH", "monitor", "MONITOR")
+}
+
+func BenchmarkLookupCommandInfoMixedCase(b *testing.B) {
+	benchmarkLookupCommandInfo(b, "wAtch", "WeTCH", "monItor", "MONiTOR")
+}