Files
gitea-MIRROR/modules/markup/markdown/math/math.go
Gal Be 42d09b71d3 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>
2026-11-24 16:19:41 +00:00

61 lines
1.8 KiB
Go

// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package math
import (
"gitea.dev/modules/markup/internal"
giteaUtil "gitea.dev/modules/util"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/util"
)
type Options struct {
Enabled bool
ParseInlineDollar bool // inline $$ xxx $$ text
ParseInlineParentheses bool // inline \( xxx \) text
ParseBlockDollar bool // block $$ multiple-line $$ text
ParseBlockSquareBrackets bool // block \[ multiple-line \] text
}
// Extension is a math extension
type Extension struct {
internalVar *internal.RenderVarMutable[internal.RenderInternal]
options Options
}
// NewExtension creates a new math extension with the provided options
func NewExtension(internalVar *internal.RenderVarMutable[internal.RenderInternal], opts ...Options) *Extension {
opt := giteaUtil.OptionalArg(opts)
r := &Extension{
internalVar: internalVar,
options: opt,
}
return r
}
// Extend extends goldmark with our parsers and renderers
func (e *Extension) Extend(m goldmark.Markdown) {
if !e.options.Enabled {
return
}
var inlines []util.PrioritizedValue
if e.options.ParseInlineParentheses {
inlines = append(inlines, util.Prioritized(NewInlineParenthesesParser(), 501))
}
inlines = append(inlines, util.Prioritized(NewInlineDollarParser(e.options.ParseInlineDollar), 502))
m.Parser().AddOptions(parser.WithInlineParsers(inlines...))
m.Parser().AddOptions(parser.WithBlockParsers(
util.Prioritized(NewBlockParser(e.options.ParseBlockDollar, e.options.ParseBlockSquareBrackets), 701),
))
m.Renderer().AddOptions(renderer.WithNodeRenderers(
util.Prioritized(NewBlockRenderer(e.internalVar), 501),
util.Prioritized(NewInlineRenderer(e.internalVar), 502),
))
}