perf(highlight): reuse one chroma HTML formatter (#40418)

`RenderCodeByLexer` created a new chroma HTML formatter on every call,
so the formatter rebuilt the CSS map of the style each time. That runs
for every fenced code block in markdown (since
https://github.com/go-gitea/gitea/pull/39751) and for every line when
the diff view highlights line by line (files over 256 KiB, or after the
full-file highlight time limit). The formatter caches that map behind a
mutex and is otherwise read-only, so one shared instance is enough.
Output is unchanged.

Local Go benchmarks, i7-9700 on Windows 11, base and patched run
alternately 6 times, medians:

| | before | after |
|---|---|---|
| 1000 lines of `services/gitdiff/gitdiff.go`, one call per line | 115.3
ms, 802k allocs | 40.8 ms, 180k allocs |
| 3-line shell code block | 142 µs, 889 allocs | 66 µs, 267 allocs |
| Markdown render of README + CONTRIBUTING + 3 docs (45 KB, 31 code
blocks) | 16.0 ms, 63.8k allocs | 14.4 ms, 45.8k allocs |

This is separate from https://github.com/go-gitea/gitea/pull/40394,
which caches highlighted lines but still creates the formatter on each
call.

Assisted-by: Claude Code:claude-opus-5-5

---------

Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
Wei-Lun Liandsilverwind authored and GitHub committed 2026-11-18 08:20:24 +00:00
1 parent e7629a62b4
commit 901859a2e2
1 file changed
+7 -6
+7 -6
View File
@@ -28,6 +28,7 @@ const sizeLimit = 1024 * 1024
type globalVarsType struct {
highlightMapping map[string]string
githubStyles *chroma.Style
htmlFormatter *chromahtml.Formatter // shared because it caches the CSS built from the style
}
var (
@@ -43,6 +44,10 @@ func globalVars() *globalVarsType {
globalVarsPtr = &globalVarsType{}
globalVarsPtr.githubStyles = styles.Get("github")
globalVarsPtr.highlightMapping = setting.GetHighlightMapping()
globalVarsPtr.htmlFormatter = chromahtml.New(chromahtml.WithClasses(true),
chromahtml.WithLineNumbers(false),
chromahtml.PreventSurroundingPre(true),
)
}
return globalVarsPtr
}
@@ -113,11 +118,6 @@ func RenderCodeByLexer(lexer chroma.Lexer, code string) template.HTML {
if lexer == lexers.Fallback {
return htmlEscape(code) // chroma is 3x slower for plain text
}
formatter := chromahtml.New(chromahtml.WithClasses(true),
chromahtml.WithLineNumbers(false),
chromahtml.PreventSurroundingPre(true),
)
iterator, err := lexer.Tokenise(nil, code)
if err != nil {
log.Error("Can't tokenize code: %v", err)
@@ -125,8 +125,9 @@ func RenderCodeByLexer(lexer chroma.Lexer, code string) template.HTML {
}
htmlBuf := &bytes.Buffer{}
vars := globalVars()
// style not used for live site but need to pass something
err = formatter.Format(htmlBuf, globalVars().githubStyles, iterator)
err = vars.htmlFormatter.Format(htmlBuf, vars.githubStyles, iterator)
if err != nil {
log.Error("Can't format code: %v", err)
return htmlEscape(code)