Explorar o código

perf(template): precompute static icon URLs at parse time

iconPath() is called a bunch of times on virtually every pages. Each call did a
fmt.Sprintf to build a string of the form
"{basePath}/icon/{checksum}/{filename}". Since both the base path and
BinaryBundles are fixed at startup, all results are determinate.

This commit precomputes the full URL for every embedded bundle once in
funcMap.Map() into a map[string]string and turns iconPath into a single map
lookup. The "_/" fallback for unknown filenames was unused, as every caller
passes a compile-time literal present in bin/, so it was removed.

Microbenchmarks are showing stupidly high gains of course, but anything macro
is non-trivial, and I gave up on it. Knowing that it removes at least one heap
allocation and a couple of reflection calls on every iconPath call is enough to
bring me joy.
jvoisin hai 3 semanas
pai
achega
102989656b
Modificáronse 2 ficheiros con 9 adicións e 6 borrados
  1. 1 1
      internal/template/engine.go
  2. 8 5
      internal/template/functions.go

+ 1 - 1
internal/template/engine.go

@@ -28,7 +28,7 @@ type Engine struct {
 func NewEngine(basePath string) *Engine {
 	return &Engine{
 		templates: make(map[string]*template.Template),
-		funcMap:   &funcMap{basePath},
+		funcMap:   &funcMap{basePath: basePath},
 	}
 }
 

+ 8 - 5
internal/template/functions.go

@@ -27,11 +27,17 @@ import (
 )
 
 type funcMap struct {
-	basePath string
+	basePath  string
+	iconPaths map[string]string
 }
 
 // Map returns a map of template functions that are compiled during template parsing.
 func (f *funcMap) Map() template.FuncMap {
+	// Pre-compute every icon URL once, as iconPath is called a lot during pages rendering.
+	f.iconPaths = make(map[string]string, len(static.BinaryBundles))
+	for filename, bundle := range static.BinaryBundles {
+		f.iconPaths[filename] = f.basePath + "/icon/" + bundle.Checksum + "/" + filename
+	}
 	return template.FuncMap{
 		"contains":         strings.Contains,
 		"csp":              csp,
@@ -155,10 +161,7 @@ func (f *funcMap) Map() template.FuncMap {
 }
 
 func (f *funcMap) iconPath(filename string) string {
-	if bundle, ok := static.BinaryBundles[filename]; ok {
-		return fmt.Sprintf("%s/icon/%s/%s", f.basePath, bundle.Checksum, filename)
-	}
-	return fmt.Sprintf("%s/icon/_/%s", f.basePath, filename)
+	return f.iconPaths[filename]
 }
 
 func (f *funcMap) iconFunc() func(string) template.HTML {