1
0
mirror of https://github.com/alecthomas/chroma.git synced 2025-03-17 20:58:08 +02:00

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
This commit is contained in:
Igor Drozdov 2020-04-26 00:55:10 +03:00 committed by GitHub
parent 0da4bd1471
commit 80f48538c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 5 deletions

View File

@ -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)

View File

@ -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")