Skip to content

Optimize table formatting hot paths#435

Open
CodingFeng101 wants to merge 1 commit into
astanin:masterfrom
CodingFeng101:codex/optimize-width-formatting
Open

Optimize table formatting hot paths#435
CodingFeng101 wants to merge 1 commit into
astanin:masterfrom
CodingFeng101:codex/optimize-width-formatting

Conversation

@CodingFeng101

Copy link
Copy Markdown

What changed

This trims two small pieces of repeated work from formatting hot paths:

  • use the already-compiled thousands-separator regex directly via .match(...) instead of routing every check through re.match(...)
  • skip _flat_list(...) when aligning single-line columns, where measured widths are already a flat list of integers

Both changes preserve the existing behavior and keep the multiline path unchanged.

Why

For larger tables, type inference calls _isnumber_with_thousands_separator() for many cells, and column alignment runs once per rendered column. Avoiding per-cell regex dispatch overhead and unnecessary single-line width flattening reduces work in the common table-rendering path.

Benchmark

Measured on Windows / Python 3.12 by loading upstream/master and this branch in the same process with timeit.repeat:

  • thousands-separator numeric detection, 19,999 values x 100: best 2.429s -> 1.310s (~46% faster)
  • single-line _align_column, 5,000 cells x 200: best 0.276s -> 0.240s (~13% faster)
  • tabulate(..., tablefmt="plain"), 5,000 rows x 10: best 1.249s -> 1.124s (~10% faster)

Validation

  • PYTHONPATH=. python -m pytest test\test_internal.py::test_align_column_decimal_with_thousand_separators test\test_internal.py::test_align_column_decimal_with_incorrect_thousand_separators test\test_output.py::test_floatfmt_thousands test\test_regression.py::test_alignment_of_decimal_numbers_with_commas -q
  • PYTHONPATH=. python -m pytest -q -> 382 passed, 1 skipped
  • python -m ruff check tabulate\__init__.py
  • python -m ruff format --check tabulate\__init__.py
  • git diff --check

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant