Skip to content

Commit

Permalink
Improve performance of lexers.Get function (#351)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
igor-drozdov committed Apr 25, 2020
1 parent 0da4bd1 commit 80f4853
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lexers/internal/api.go
Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions lexers/lexers_test.go
Expand Up @@ -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 <key>.<key> and validation data is in the form <key>.<key>.expected.
func TestLexers(t *testing.T) {
files, err := ioutil.ReadDir("testdata")
Expand Down

0 comments on commit 80f4853

Please sign in to comment.