From 56e2a65ec1b8de5173d8a44e34f1bf0edb5f28df Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Tue, 2 Apr 2024 20:14:07 +0200 Subject: [PATCH] Improved performance --- README.md | 9 +++++---- Render.go | 46 ++++++++++++++++++++++------------------------ 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 089dff5..b0d3057 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,8 @@ A markdown renderer that supports only a subset of the CommonMark spec in order ## Features -- Code +- Code blocks +- Formatting (bold, italic, monospace) - Links - Lists - Headers @@ -47,9 +48,9 @@ coverage: 100.0% of statements ## Benchmarks ``` -BenchmarkSmall-12 8109500 145.1 ns/op 32 B/op 1 allocs/op -BenchmarkMedium-12 556713 1906 ns/op 512 B/op 1 allocs/op -BenchmarkLarge-12 218116 4588 ns/op 2560 B/op 2 allocs/op +BenchmarkSmall-12 5986922 187.5 ns/op 32 B/op 1 allocs/op +BenchmarkMedium-12 1000000 1077 ns/op 512 B/op 1 allocs/op +BenchmarkLarge-12 255178 4055 ns/op 2560 B/op 2 allocs/op ``` ## License diff --git a/Render.go b/Render.go index 6679a00..3bc3df4 100644 --- a/Render.go +++ b/Render.go @@ -249,36 +249,37 @@ func (r *renderer) closeTables() { // writeText converts inline markdown to HTML. func (r *renderer) writeText(markdown string) { var ( - i = 0 - tokenStart = 0 - ) - - var ( - textStart = -1 - textEnd = -1 - urlStart = -1 - codeStart = -1 - emStart = -1 - strongStart = -1 - parentheses = 0 + tokenStart = 0 + searchStart = 0 + linkTextStart = -1 + linkTextEnd = -1 + urlStart = -1 + codeStart = -1 + emStart = -1 + strongStart = -1 + parentheses = 0 ) for { - if i >= len(markdown) { + i := strings.IndexAny(markdown[searchStart:], "[]()`*_") + + if i == -1 { r.WriteString(html.EscapeString(markdown[tokenStart:])) return } + i += searchStart + searchStart = i + 1 c := markdown[i] switch c { case '[': r.WriteString(html.EscapeString(markdown[tokenStart:i])) tokenStart = i - textStart = i + linkTextStart = i case ']': - textEnd = i + linkTextEnd = i case '(': if parentheses == 0 { @@ -290,8 +291,8 @@ func (r *renderer) writeText(markdown string) { case ')': parentheses-- - if parentheses == 0 && textStart >= 0 && textEnd >= 0 && urlStart >= 0 { - linkText := markdown[textStart+1 : textEnd] + if parentheses == 0 && linkTextStart >= 0 && linkTextEnd >= 0 && urlStart >= 0 { + linkText := markdown[linkTextStart+1 : linkTextEnd] linkURL := markdown[urlStart+1 : i] r.WriteString("") - textStart = -1 - textEnd = -1 + linkTextStart = -1 + linkTextEnd = -1 urlStart = -1 tokenStart = i + 1 @@ -329,9 +330,8 @@ func (r *renderer) writeText(markdown string) { r.WriteString(html.EscapeString(markdown[strongStart:i])) r.WriteString("") strongStart = -1 - - i++ - tokenStart = i + 1 + tokenStart = i + 2 + searchStart = tokenStart } else if emStart != -1 { r.WriteString("") r.WriteString(html.EscapeString(markdown[emStart:i])) @@ -344,8 +344,6 @@ func (r *renderer) writeText(markdown string) { emStart = i + 1 } } - - i++ } }