Skip to content

Commit 19f8b23

Browse files
committed
feat(template): optimize sprig function init
Pre-compute Sprig template functions during package init. Avoids repeated map allocation and string concatenation for Sprig functions on every template execution, addressing performance overhead reported in #2031. Signed-off-by: Ville Vesilehto <[email protected]>
1 parent 1adb94d commit 19f8b23

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

template/template.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,19 @@ var (
3434
ErrMissingReaderFunction = errors.New("template: missing a reader function")
3535
)
3636

37+
var (
38+
sprigFuncMap template.FuncMap
39+
)
40+
41+
func init() {
42+
sprigFuncMap = make(template.FuncMap, len(sprig.TxtFuncMap()))
43+
// Add the Sprig functions to the funcmap
44+
for k, v := range sprig.TxtFuncMap() {
45+
target := "sprig_" + k
46+
sprigFuncMap[target] = v
47+
}
48+
}
49+
3750
// Template is the internal representation of an individual template to process.
3851
// The template retains the relationship between its contents and is
3952
// responsible for it's own execution.
@@ -436,10 +449,9 @@ func funcMap(i *funcMapInput) template.FuncMap {
436449
"spew_sprintf": spewSprintf,
437450
}
438451

439-
// Add the Sprig functions to the funcmap
440-
for k, v := range sprig.TxtFuncMap() {
441-
target := "sprig_" + k
442-
r[target] = v
452+
// Add the pre-computed Sprig functions to the funcmap
453+
for k, v := range sprigFuncMap {
454+
r[k] = v
443455
}
444456

445457
// Add external functions

0 commit comments

Comments
 (0)