From de4a06f6fca41631eb6e57cbbd3c08b785cd72e9 Mon Sep 17 00:00:00 2001 From: Igor Drozdov Date: Sun, 26 Apr 2020 00:55:10 +0300 Subject: [PATCH] Improve performance of lexers.Get function (#351) * Benchmark test for lexers.Get function * Improve performance of lexers.Get function Look for a lexer by file extension only when it failed to find a lexer by name --- lexers/internal/api.go | 11 ++++++----- lexers/lexers_test.go | 6 ++++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/lexers/internal/api.go b/lexers/internal/api.go index 002997a56..08ec6ff7f 100644 --- a/lexers/internal/api.go +++ b/lexers/internal/api.go @@ -37,19 +37,20 @@ func Names(withAliases bool) []string { // Get a Lexer by name, alias or file extension. func Get(name string) chroma.Lexer { - candidates := chroma.PrioritisedLexers{} if lexer := Registry.byName[name]; lexer != nil { - candidates = append(candidates, lexer) + return lexer } if lexer := Registry.byAlias[name]; lexer != nil { - candidates = append(candidates, lexer) + return lexer } if lexer := Registry.byName[strings.ToLower(name)]; lexer != nil { - candidates = append(candidates, lexer) + return lexer } if lexer := Registry.byAlias[strings.ToLower(name)]; lexer != nil { - candidates = append(candidates, lexer) + return lexer } + + candidates := chroma.PrioritisedLexers{} // Try file extension. if lexer := Match("filename." + name); lexer != nil { candidates = append(candidates, lexer) diff --git a/lexers/lexers_test.go b/lexers/lexers_test.go index 5cdbdb223..34496dd85 100644 --- a/lexers/lexers_test.go +++ b/lexers/lexers_test.go @@ -38,6 +38,12 @@ func TestGet(t *testing.T) { }) } +func BenchmarkGet(b *testing.B) { + for i := 0; i < b.N; i++ { + lexers.Get("go") + } +} + // Test source files are in the form . and validation data is in the form ..expected. func TestLexers(t *testing.T) { files, err := ioutil.ReadDir("testdata")