Skip to content

Commit 6da0ca6

Browse files
authored
performance: slightly faster line wrap
1 parent 49cc084 commit 6da0ca6

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

pyproject.toml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,15 @@ commands = [
145145
["python", "fuzzer/fuzz.py", "{toxworkdir}/fuzzer-corpus", { replace = "posargs", default = ["-len_control=10000"], extend = true }],
146146
]
147147

148+
[tool.tox.env."benchmark"]
149+
description = "benchmark mdformat against local doc files"
150+
commands = [
151+
["python", "-c", "print('Wrap mode: keep')"],
152+
["python", "-m", "timeit", "from mdformat._cli import run", 'run(["README.md", "docs/", "--check"])'],
153+
["python", "-c", "print('Wrap mode: 50')"],
154+
["python", "-m", "timeit", "from mdformat._cli import run", 'run(["README.md", "docs/", "--check", "--wrap", "50"])'],
155+
]
156+
148157

149158
[tool.coverage.run]
150159
source = ["mdformat"]

src/mdformat/renderer/_context.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
# A marker used to indicate location of a character that should be preserved
4141
# during word wrap. Should be converted to the actual character after wrap.
4242
PRESERVE_CHAR = "\x00"
43+
RE_PRESERVE_CHAR = re.compile(re.escape(PRESERVE_CHAR))
4344

4445

4546
def make_render_children(separator: str) -> Render:
@@ -372,10 +373,8 @@ def _prepare_wrap(text: str) -> tuple[str, str]:
372373

373374

374375
def _recover_preserve_chars(text: str, replacements: str) -> str:
375-
replacement_iterator = iter(replacements)
376-
return "".join(
377-
next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text
378-
)
376+
iter_replacements = iter(replacements)
377+
return RE_PRESERVE_CHAR.sub(lambda _: next(iter_replacements), text)
379378

380379

381380
def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901

tests/test_for_profiler.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,5 @@ def test_for_profiler():
2424
docs_path = PROJECT_ROOT / "docs"
2525
readme_path = PROJECT_ROOT / "README.md"
2626
assert run([str(docs_path), str(readme_path), "--check"]) == 0
27+
# Also profile --wrap=INT code
28+
run([str(docs_path), str(readme_path), "--check", "--wrap", "50"])

0 commit comments

Comments
 (0)