Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

performance: Slightly faster line wrap #475

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,15 @@ commands = [
["python", "fuzzer/fuzz.py", "{toxworkdir}/fuzzer-corpus", { replace = "posargs", default = ["-len_control=10000"], extend = true }],
]

[tool.tox.env."benchmark"]
description = "benchmark mdformat against local doc files"
commands = [
["python", "-c", "print('Wrap mode: keep')"],
["python", "-m", "timeit", "from mdformat._cli import run", 'run(["README.md", "docs/", "--check"])'],
["python", "-c", "print('Wrap mode: 50')"],
["python", "-m", "timeit", "from mdformat._cli import run", 'run(["README.md", "docs/", "--check", "--wrap", "50"])'],
]


[tool.coverage.run]
source = ["mdformat"]
Expand Down
7 changes: 3 additions & 4 deletions src/mdformat/renderer/_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
# A marker used to indicate location of a character that should be preserved
# during word wrap. Should be converted to the actual character after wrap.
PRESERVE_CHAR = "\x00"
RE_PRESERVE_CHAR = re.compile(re.escape(PRESERVE_CHAR))


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


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


def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901
Expand Down
2 changes: 2 additions & 0 deletions tests/test_for_profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ def test_for_profiler():
docs_path = PROJECT_ROOT / "docs"
readme_path = PROJECT_ROOT / "README.md"
assert run([str(docs_path), str(readme_path), "--check"]) == 0
# Also profile --wrap=INT code
run([str(docs_path), str(readme_path), "--check", "--wrap", "50"])