perf(markdown): stop building a new markdown converter for every render (#40515)

Each render built a new goldmark converter. For short texts, such as
comments, this was most of the cost. Now `render` reuses converters from
a `sync.Pool`, as the TODO in `SpecializedMarkdown` suggested. Each
converter gets the `RenderInternal` of the render. The HTML output does
not change.

| Benchmark | Before | After | Allocs |
|---|---:|---:|---|
| Comment | 85.0 µs | 46.0 µs | 502 → 207 |
| `BenchmarkMarkdownRender` | 100.5 µs | 62.8 µs | 536 → 241 |
| README | 1.51 ms | 1.50 ms | 9679 → 9384 |

No benchmark got slower (AMD EPYC 9V74, Go 1.27.4, 24 rounds).

Checks:
- `go test ./modules/markup/...` and golangci-lint pass.
- Old and new HTML matched on 20,000 random documents.
- Parallel renders pass with `-race`.

Claude was used for this change. I reviewed and tested it.

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
authored and GitHub committed 2026-11-24 16:19:41 +00:00
1 parent b1a6cdadc8
commit 42d09b71d3
14 files changed
+92 -55

No files matched your search

@@ -21,6 +21,10 @@ var reAttrClass = sync.OnceValue(func() *regexp.Regexp {
return regexp.MustCompile(`(<[^>]+)\s+class="([^"]+)"([^>]*>)`)
})
type RenderVarMutable[T any] struct {
Value *T
}
// RenderInternal also works without initialization
// If no initialization (no secureID), it will not protect any attributes and return the original name&value
type RenderInternal struct {
+1 -1
View File
@@ -88,7 +88,7 @@ func nodeToDetails(g *ASTTransformer, meta *yaml.Node) ast.Node {
}
}
details := NewDetails()
details.SetAttributeString(g.renderInternal.SafeAttr("class"), g.renderInternal.SafeValue("frontmatter-content"))
details.SetAttributeString(g.internalVar.Value.SafeAttr("class"), g.internalVar.Value.SafeValue("frontmatter-content"))
summary := NewSummary()
summaryInnerHTML := htmlutil.HTMLFormat("%s %s", svg.RenderHTML("octicon-table", 12), strings.Join(keys, ", "))
summary.AppendChild(summary, NewRawHTML(summaryInnerHTML))
+9 -9
View File
@@ -23,13 +23,13 @@ import (
// ASTTransformer is a default transformer of the goldmark tree.
type ASTTransformer struct {
renderInternal *internal.RenderInternal
internalVar *internal.RenderVarMutable[internal.RenderInternal]
attentionTypes container.Set[string]
}
func NewASTTransformer(renderInternal *internal.RenderInternal) *ASTTransformer {
func NewASTTransformer(internalVar *internal.RenderVarMutable[internal.RenderInternal]) *ASTTransformer {
return &ASTTransformer{
renderInternal: renderInternal,
internalVar: internalVar,
attentionTypes: container.SetOf("note", "tip", "important", "warning", "caution"),
}
}
@@ -119,10 +119,10 @@ func filterFeedExcerpt(parent ast.Node) {
}
// NewHTMLRenderer creates a HTMLRenderer to render in the gitea form.
func NewHTMLRenderer(renderInternal *internal.RenderInternal, opts ...html.Option) renderer.NodeRenderer {
func NewHTMLRenderer(internalVar *internal.RenderVarMutable[internal.RenderInternal], opts ...html.Option) renderer.NodeRenderer {
r := &HTMLRenderer{
renderInternal: renderInternal,
Config: html.NewConfig(),
internalVar: internalVar,
Config: html.NewConfig(),
}
for _, opt := range opts {
opt.SetHTMLOption(&r.Config)
@@ -134,7 +134,7 @@ func NewHTMLRenderer(renderInternal *internal.RenderInternal, opts ...html.Optio
// renders gitea specific features.
type HTMLRenderer struct {
html.Config
renderInternal *internal.RenderInternal
internalVar *internal.RenderVarMutable[internal.RenderInternal]
}
// RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs.
@@ -157,7 +157,7 @@ func (r *HTMLRenderer) renderCodeBlock(w util.BufWriter, source []byte, n ast.No
language = string(fenced.Language(source))
}
preAttrs, codeAttrs := highlight.CodeBlockAttributes(language)
err := r.renderInternal.FormatWithSafeAttrsf(w, `<div class="code-block-container code-overflow-scroll"><pre %s><code %s>`, preAttrs, codeAttrs)
err := r.internalVar.Value.FormatWithSafeAttrsf(w, `<div class="code-block-container code-overflow-scroll"><pre %s><code %s>`, preAttrs, codeAttrs)
if err != nil {
return ast.WalkStop, err
}
@@ -238,7 +238,7 @@ func (r *HTMLRenderer) renderRawHTML(w util.BufWriter, source []byte, node ast.N
return ast.WalkContinue, nil
}
n := node.(*RawHTML) //nolint:forcetypeassert // registered for KindRawHTML only
_, err := w.WriteString(string(r.renderInternal.ProtectSafeAttrs(n.rawHTML)))
_, err := w.WriteString(string(r.internalVar.Value.ProtectSafeAttrs(n.rawHTML)))
if err != nil {
return ast.WalkStop, err
}
+49 -17
View File
@@ -12,11 +12,13 @@ import (
"io"
"slices"
"strings"
"sync"
"gitea.dev/modules/htmlutil"
"gitea.dev/modules/log"
"gitea.dev/modules/markup"
"gitea.dev/modules/markup/common"
"gitea.dev/modules/markup/internal"
"gitea.dev/modules/markup/markdown/math"
"gitea.dev/modules/setting"
giteautil "gitea.dev/modules/util"
@@ -28,7 +30,7 @@ import (
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/text"
"github.com/yuin/goldmark/util"
gmutil "github.com/yuin/goldmark/util"
)
var (
@@ -89,21 +91,19 @@ func (s *goldmarkEmphasisParser) Parse(parent ast.Node, block text.Reader, pc pa
func goldmarkDefaultParser() parser.Parser {
return parser.NewParser(parser.WithBlockParsers(parser.DefaultBlockParsers()...),
parser.WithInlineParsers([]util.PrioritizedValue{
util.Prioritized(parser.NewCodeSpanParser(), 100),
util.Prioritized(parser.NewLinkParser(), 200),
util.Prioritized(parser.NewAutoLinkParser(), 300),
util.Prioritized(parser.NewRawHTMLParser(), 400),
util.Prioritized(goldmarkNewEmphasisParser(), 500),
parser.WithInlineParsers([]gmutil.PrioritizedValue{
gmutil.Prioritized(parser.NewCodeSpanParser(), 100),
gmutil.Prioritized(parser.NewLinkParser(), 200),
gmutil.Prioritized(parser.NewAutoLinkParser(), 300),
gmutil.Prioritized(parser.NewRawHTMLParser(), 400),
gmutil.Prioritized(goldmarkNewEmphasisParser(), 500),
}...),
parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...),
)
}
// SpecializedMarkdown sets up the Gitea specific markdown extensions
func SpecializedMarkdown(ctx *markup.RenderContext) goldmark.Markdown {
// TODO: it could use a pool to cache the renderers to reuse them with different contexts
// at the moment it is fast enough (see the benchmarks)
func specializedMarkdown() (goldmark.Markdown, *internal.RenderVarMutable[internal.RenderInternal]) {
internalVar := &internal.RenderVarMutable[internal.RenderInternal]{}
return goldmark.New(
goldmark.WithParser(goldmarkDefaultParser()),
goldmark.WithExtensions(
@@ -112,7 +112,7 @@ func SpecializedMarkdown(ctx *markup.RenderContext) goldmark.Markdown {
extension.TaskList,
extension.DefinitionList,
common.FootnoteExtension,
math.NewExtension(&ctx.RenderInternal, math.Options{
math.NewExtension(internalVar, math.Options{
Enabled: setting.Markdown.EnableMath,
ParseInlineDollar: setting.Markdown.MathCodeBlockOptions.ParseInlineDollar,
ParseInlineParentheses: setting.Markdown.MathCodeBlockOptions.ParseInlineParentheses, // this is a bad syntax "\( ... \)", it conflicts with normal markdown escaping
@@ -122,19 +122,47 @@ func SpecializedMarkdown(ctx *markup.RenderContext) goldmark.Markdown {
),
goldmark.WithParserOptions(
parser.WithAttribute(),
parser.WithASTTransformers(util.Prioritized(NewASTTransformer(&ctx.RenderInternal), 10000)),
parser.WithASTTransformers(gmutil.Prioritized(NewASTTransformer(internalVar), 10000)),
),
goldmark.WithRendererOptions(
html.WithUnsafe(),
renderer.WithNodeRenderers(util.Prioritized(NewHTMLRenderer(&ctx.RenderInternal), 10)),
renderer.WithNodeRenderers(gmutil.Prioritized(NewHTMLRenderer(internalVar), 10)),
),
)
), internalVar
}
type sharedMarkdownRender struct {
converter goldmark.Markdown
internalVar *internal.RenderVarMutable[internal.RenderInternal]
}
var SharedMarkdownRenderPool = giteautil.OnceValue[*sync.Pool]{
Func: func() *sync.Pool {
return &sync.Pool{
New: func() any {
r, v := specializedMarkdown()
return &sharedMarkdownRender{converter: r, internalVar: v}
},
}
},
}
func acquireMarkdownRender(ctx *markup.RenderContext) (*sharedMarkdownRender, func()) {
r, _ := SharedMarkdownRenderPool.Value().Get().(*sharedMarkdownRender)
r.internalVar.Value = &ctx.RenderInternal
return r, func() {
r.internalVar.Value = nil
SharedMarkdownRenderPool.Value().Put(r)
}
}
// render calls goldmark render to convert Markdown to HTML
// NOTE: The output of this method MUST get sanitized separately!!!
func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
converter := SpecializedMarkdown(ctx)
sharedRender, release := acquireMarkdownRender(ctx)
defer release()
converter := sharedRender.converter
lw := &limitWriter{
w: output,
limit: setting.UI.MaxDisplayFileSize * 3,
@@ -234,7 +262,11 @@ func FeedExcerpt(ctx context.Context, content string) string {
pc.Set(renderConfigKey, &RenderConfig{})
start, texts := len(content), []text.Segment(nil)
mdParser := SpecializedMarkdown(rctx).Parser()
sharedRender, release := acquireMarkdownRender(rctx)
defer release()
converter := sharedRender.converter
mdParser := converter.Parser()
mdReader := text.NewReader([]byte(content))
mdWalker := func(node ast.Node, entering bool) (ast.WalkStatus, error) {
if entering && node.Type() == ast.TypeBlock && node.Lines().Len() > 0 {
@@ -25,6 +25,8 @@ func TestAttention(t *testing.T) {
defer svg.MockIcon("octicon-alert")()
defer svg.MockIcon("octicon-stop")()
defer test.MockVariableValue(&setting.Markdown.MathCodeBlockOptions, setting.MarkdownMathCodeBlockOptions{})()
markdown.SharedMarkdownRenderPool.Reset()
defer markdown.SharedMarkdownRenderPool.Reset()
test := func(input, expected string) {
result, err := markdown.RenderString(markup.NewTestRenderContext(), input)
@@ -52,6 +54,7 @@ func TestAttention(t *testing.T) {
for _, parseInlineParentheses := range []bool{false, true} {
setting.Markdown.MathCodeBlockOptions.ParseInlineParentheses = parseInlineParentheses
markdown.SharedMarkdownRenderPool.Reset()
test("> \\[!NOTE\\]\n> text", renderAttention("note", "octicon-info")+"\n<p>text</p>\n</blockquote>")
test(`> \[!UNKNOWN\]`, "<blockquote>\n<p>[!UNKNOWN]</p>\n</blockquote>")
test(`> \[NOTE\]`, "<blockquote>\n<p>[NOTE]</p>\n</blockquote>")
@@ -10,13 +10,6 @@ import (
"gitea.dev/modules/markup/markdown"
)
func BenchmarkSpecializedMarkdown(b *testing.B) {
// 240856 4719 ns/op
for b.Loop() {
markdown.SpecializedMarkdown(&markup.RenderContext{})
}
}
func BenchmarkMarkdownRender(b *testing.B) {
// 23202 50840 ns/op
for b.Loop() {
@@ -18,6 +18,8 @@ const nl = "\n"
func TestMathRender(t *testing.T) {
defer test.MockVariableValue(&setting.Markdown.MathCodeBlockOptions, setting.MarkdownMathCodeBlockOptions{ParseInlineDollar: true, ParseInlineParentheses: true})()
SharedMarkdownRenderPool.Reset()
defer SharedMarkdownRenderPool.Reset()
testcases := []struct {
testcase string
expected string
@@ -127,6 +129,8 @@ func TestMathRender(t *testing.T) {
func TestMathRenderBlockIndent(t *testing.T) {
defer test.MockVariableValue(&setting.Markdown.MathCodeBlockOptions, setting.MarkdownMathCodeBlockOptions{ParseBlockDollar: true, ParseBlockSquareBrackets: true})()
SharedMarkdownRenderPool.Reset()
defer SharedMarkdownRenderPool.Reset()
testcases := []struct {
name string
testcase string
@@ -262,7 +266,9 @@ x
func TestMathRenderOptions(t *testing.T) {
defer test.MockVariableValue(&setting.Markdown.MathCodeBlockOptions, setting.MarkdownMathCodeBlockOptions{})()
defer SharedMarkdownRenderPool.Reset()
test := func(t *testing.T, expected, input string) {
SharedMarkdownRenderPool.Reset()
res, err := RenderString(markup.NewTestRenderContext(), input)
assert.NoError(t, err)
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(res)), "input: %s", input)
@@ -27,12 +27,12 @@ import (
// BlockRenderer represents a renderer for math Blocks
type BlockRenderer struct {
renderInternal *internal.RenderInternal
internalVar *internal.RenderVarMutable[internal.RenderInternal]
}
// NewBlockRenderer creates a new renderer for math Blocks
func NewBlockRenderer(renderInternal *internal.RenderInternal) renderer.NodeRenderer {
return &BlockRenderer{renderInternal: renderInternal}
func NewBlockRenderer(internalVar *internal.RenderVarMutable[internal.RenderInternal]) renderer.NodeRenderer {
return &BlockRenderer{internalVar: internalVar}
}
// RegisterFuncs registers the renderer for math Blocks
@@ -52,7 +52,7 @@ func (r *BlockRenderer) renderBlock(w util.BufWriter, source []byte, node gast.N
n := node.(*Block) //nolint:forcetypeassert // registered for KindBlock only
if entering {
codeHTML := giteaUtil.Iif[template.HTML](n.Inline, "", `<pre class="code-block is-loading">`) + `<code class="language-math">`
_, _ = w.WriteString(string(r.renderInternal.ProtectSafeAttrs(codeHTML)))
_, _ = w.WriteString(string(r.internalVar.Value.ProtectSafeAttrs(codeHTML)))
r.writeLines(w, source, n)
} else {
_, _ = w.WriteString(`</code>` + giteaUtil.Iif(n.Inline, "", `</pre>`) + "\n")
@@ -18,17 +18,17 @@ import (
// InlineRenderer is an inline renderer
type InlineRenderer struct {
renderInternal *internal.RenderInternal
internalVar *internal.RenderVarMutable[internal.RenderInternal]
}
// NewInlineRenderer returns a new renderer for inline math
func NewInlineRenderer(renderInternal *internal.RenderInternal) renderer.NodeRenderer {
return &InlineRenderer{renderInternal: renderInternal}
func NewInlineRenderer(internalVar *internal.RenderVarMutable[internal.RenderInternal]) renderer.NodeRenderer {
return &InlineRenderer{internalVar: internalVar}
}
func (r *InlineRenderer) renderInline(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {
if entering {
_, _ = w.WriteString(string(r.renderInternal.ProtectSafeAttrs(`<code class="language-math">`)))
_, _ = w.WriteString(string(r.internalVar.Value.ProtectSafeAttrs(`<code class="language-math">`)))
for c := n.FirstChild(); c != nil; c = c.NextSibling() {
segment := c.(*ast.Text).Segment //nolint:forcetypeassert // an inline math node only holds text children
value := util.EscapeHTML(segment.Value(source))
+7 -7
View File
@@ -23,16 +23,16 @@ type Options struct {
// Extension is a math extension
type Extension struct {
renderInternal *internal.RenderInternal
options Options
internalVar *internal.RenderVarMutable[internal.RenderInternal]
options Options
}
// NewExtension creates a new math extension with the provided options
func NewExtension(renderInternal *internal.RenderInternal, opts ...Options) *Extension {
func NewExtension(internalVar *internal.RenderVarMutable[internal.RenderInternal], opts ...Options) *Extension {
opt := giteaUtil.OptionalArg(opts)
r := &Extension{
renderInternal: renderInternal,
options: opt,
internalVar: internalVar,
options: opt,
}
return r
}
@@ -54,7 +54,7 @@ func (e *Extension) Extend(m goldmark.Markdown) {
util.Prioritized(NewBlockParser(e.options.ParseBlockDollar, e.options.ParseBlockSquareBrackets), 701),
))
m.Renderer().AddOptions(renderer.WithNodeRenderers(
util.Prioritized(NewBlockRenderer(e.renderInternal), 501),
util.Prioritized(NewInlineRenderer(e.renderInternal), 502),
util.Prioritized(NewBlockRenderer(e.internalVar), 501),
util.Prioritized(NewInlineRenderer(e.internalVar), 502),
))
}
@@ -33,7 +33,7 @@ func (r *HTMLRenderer) renderAttention(w util.BufWriter, source []byte, node ast
octiconName = "info"
}
svgHTML := svg.RenderHTML("octicon-"+octiconName, 16, "attention-icon attention-"+n.AttentionType)
_, _ = w.WriteString(string(r.renderInternal.ProtectSafeAttrs(svgHTML)))
_, _ = w.WriteString(string(r.internalVar.Value.ProtectSafeAttrs(svgHTML)))
}
return ast.WalkContinue, nil
}
@@ -136,13 +136,13 @@ func (g *ASTTransformer) transformBlockquote(v *ast.Blockquote, reader text.Read
}
// color the blockquote
v.SetAttributeString(g.renderInternal.SafeAttr("class"), []byte(g.renderInternal.SafeValue("attention-header attention-"+attentionType)))
v.SetAttributeString(g.internalVar.Value.SafeAttr("class"), []byte(g.internalVar.Value.SafeValue("attention-header attention-"+attentionType)))
// create an emphasis to make it bold
attentionParagraph := ast.NewParagraph()
g.applyElementDir(attentionParagraph)
emphasis := ast.NewEmphasis(2)
emphasis.SetAttributeString(g.renderInternal.SafeAttr("class"), []byte(g.renderInternal.SafeValue("attention-"+attentionType)))
emphasis.SetAttributeString(g.internalVar.Value.SafeAttr("class"), []byte(g.internalVar.Value.SafeValue("attention-"+attentionType)))
attentionAstString := ast.NewString([]byte(cases.Title(language.English).String(attentionType)))
@@ -39,7 +39,7 @@ func (r *HTMLRenderer) renderCodeSpan(w util.BufWriter, source []byte, n ast.Nod
r.Writer.RawWrite(w, value)
}
case *ColorPreview:
_ = r.renderInternal.FormatWithSafeAttrsf(w, `<span class="color-preview" style="background-color: %s"></span>`, v.Color)
_ = r.internalVar.Value.FormatWithSafeAttrsf(w, `<span class="color-preview" style="background-color: %s"></span>`, v.Color)
}
}
return ast.WalkSkipChildren, nil
+1 -1
View File
@@ -42,7 +42,7 @@ func (g *ASTTransformer) transformList(_ *markup.RenderContext, v *ast.List, rc
if !ok {
continue
}
listItem.SetAttributeString(g.renderInternal.SafeAttr("class"), []byte(g.renderInternal.SafeValue("task-list-item")))
listItem.SetAttributeString(g.internalVar.Value.SafeAttr("class"), []byte(g.internalVar.Value.SafeValue("task-list-item")))
if lines := block.Lines(); lines.Len() > 0 {
checkBox.SetAttributeString("data-source-position", []byte(strconv.Itoa(rc.metaLength+lines.At(0).Start)))
}
-1
View File
@@ -241,7 +241,6 @@ space</p>
`
assert.Equal(t, expected, string(newTestRenderUtils(t).MarkdownToHtml(testInput())))
defer test.MockVariableValue(&setting.Markdown.MathCodeBlockOptions, setting.MarkdownMathCodeBlockOptions{ParseBlockDollar: true})()
for _, tc := range []struct {
name string
input string