Skip to content

Commit c1cf230

Browse files
committed
perf(lsp): compile naming-diagnostic regexes once, not per call
lspNamingDiagnostic recompiled 3 constant regexes on every call; LSP runs diagnostics on every document change, so regexp.compile was ~67% of LSPComputeDiagnostics's allocations. Hoisted to package-level vars. LSPComputeDiagnostics: 186->47 allocs/op, 23922->8475 B/op, 12162->6061 ns/op. Behaviour byte-identical (LSP tests green). Co-Authored-By: Virgil <virgil@lethean.io>
1 parent 7194031 commit c1cf230

1 file changed

Lines changed: 13 additions & 9 deletions

File tree

lsp.go

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -525,22 +525,26 @@ func lspSporDiagnostic(uri string, content []byte) []LSPDiagnostic {
525525
return diags
526526
}
527527

528+
// lspNaming{Top,Method,Test}Re are compiled once at package init. The
529+
// patterns are constant, and LSP runs diagnostics on every document
530+
// change — recompiling them per call made regexp.compile ~67% of
531+
// LSPComputeDiagnostics's allocations. Hoisting cuts ~150 allocs/call.
532+
var (
533+
lspNamingTopRe = Regex(`^func ([A-Za-z][A-Za-z0-9_]*)\s*[\[(]`).Value.(*Regexp)
534+
lspNamingMethodRe = Regex(`^func \([^)]*?\*?([A-Za-z][A-Za-z0-9_]*)(?:\[[^\]]+\])?\) ([A-Za-z][A-Za-z0-9_]*)\s*[\[(]`).Value.(*Regexp)
535+
lspNamingTestRe = Regex(`^func (Test[A-Za-z0-9_]+)\s*\(`).Value.(*Regexp)
536+
)
537+
528538
// lspNamingDiagnostic flags production symbols that do not have the
529539
// Test*_{Symbol}_{Good,Bad,Ugly} triplet in the same directory's tests.
530540
func lspNamingDiagnostic(uri string, content []byte) []LSPDiagnostic {
531541
if !HasSuffix(uri, ".go") || HasSuffix(uri, "_test.go") {
532542
return nil
533543
}
534544

535-
topResult := Regex(`^func ([A-Za-z][A-Za-z0-9_]*)\s*[\[(]`)
536-
methodResult := Regex(`^func \([^)]*?\*?([A-Za-z][A-Za-z0-9_]*)(?:\[[^\]]+\])?\) ([A-Za-z][A-Za-z0-9_]*)\s*[\[(]`)
537-
testResult := Regex(`^func (Test[A-Za-z0-9_]+)\s*\(`)
538-
if !topResult.OK || !methodResult.OK || !testResult.OK {
539-
return nil
540-
}
541-
top := topResult.Value.(*Regexp)
542-
method := methodResult.Value.(*Regexp)
543-
test := testResult.Value.(*Regexp)
545+
top := lspNamingTopRe
546+
method := lspNamingMethodRe
547+
test := lspNamingTestRe
544548

545549
path := TrimPrefix(uri, "file://")
546550
dir := PathDir(path)

0 commit comments

Comments
 (0)