python-tabulate icon indicating copy to clipboard operation
python-tabulate copied to clipboard

Optimize table formatting hot paths

Open CodingFeng101 opened this issue 5 months ago • 0 comments

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

CodingFeng101 avatar Jun 29 '26 15:06 CodingFeng101