Skip to content

Commit a1ed2f8

Browse files
internal/codegen: cache pattern matching compilations
Type overrides are checked linearly for every codegen'd type. That linear check currently compiles a regexp pattern for every override that's considered. This commit adds a simple memoizing cache so that each pattern is only ever compiled once. This dramatically improves performance of sqlc for users who have many overrides. ngrok's usage of sqlc generate sees a 10x speedup from this change (4s -> 0.4s).
1 parent d64a68b commit a1ed2f8

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

internal/codegen/sdk/sdk.go

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package sdk
22

33
import (
4+
"sync"
5+
46
"github.com/kyleconroy/sqlc/internal/pattern"
57
"github.com/kyleconroy/sqlc/internal/plugin"
68
)
@@ -13,11 +15,26 @@ func DataType(n *plugin.Identifier) string {
1315
}
1416
}
1517

18+
var (
19+
patternCache = make(map[string]*pattern.Match)
20+
mu sync.RWMutex
21+
)
22+
1623
func MatchString(pat, target string) bool {
17-
matcher, err := pattern.MatchCompile(pat)
18-
if err != nil {
19-
panic(err)
24+
mu.RLock()
25+
matcher, ok := patternCache[pat]
26+
mu.RUnlock()
27+
if !ok {
28+
var err error
29+
matcher, _ = pattern.MatchCompile(pat)
30+
if err != nil {
31+
panic(err)
32+
}
33+
mu.Lock()
34+
patternCache[pat] = matcher
35+
mu.Unlock()
2036
}
37+
2138
return matcher.MatchString(target)
2239
}
2340

0 commit comments

Comments
 (0)