Skip to content

perf: optimize cell type inference, ANSI stripping, and multiline checks - #518

Open
millisdoe-glitch wants to merge 1 commit into
astanin:masterfrom
millisdoe-glitch:perf/optimize-cell-type-and-ansi-checks
Open

millisdoe-glitch wants to merge 1 commit into
astanin:masterfrom
millisdoe-glitch:perf/optimize-cell-type-and-ansi-checks

Conversation

@millisdoe-glitch

Copy link
Copy Markdown

Summary

This PR optimizes performance bottlenecks in cell type deduction, ANSI code stripping, and multiline string checks during table formatting:

  1. _isint():

    • Added an immediate if type(string) is float: return False fast path.
    • Previously, Python float instances entered hasattr(string, "is_integer") (which evaluates to True on floats), triggering str(type(string)) string creation and .startswith("<class 'numpy.int") checks on every single float cell in the table.
  2. _type() & _isnumber_with_thousands_separator():

    • Flattened numeric type checking so _isnumber_with_thousands_separator(string) regex is evaluated at most once per non-integer cell (previously called twice in consecutive elif branches).
    • Used compiled pattern method _float_with_thousands_separators.match(string) directly instead of module-level re.match(...).
  3. _strip_ansi():

    • Added fast-path check if "\x1b" not in s: return s (and b"\x1b" for bytestrings). Plain text cells (the vast majority of table inputs) skip _ansi_codes.sub() regex traversal completely (~5.3x faster for plain strings).
  4. _is_multiline():

    • Replaced re.search(_multiline_codes, s) with fast C-level substring checks "\n" in s or "\r" in s (~10.9x faster).
  5. _afterpoint():

    • Replaced string.lower().rfind("e") with max(string.rfind("e"), string.rfind("E")), eliminating intermediate lowercase string allocations.

Benchmark & Profiling

On a 1000x10 mixed string/numeric table (tabulate(data, headers=headers, tablefmt="grid")):

  • Total function calls: reduced from 475,445 to 395,428 (80,000+ function calls eliminated).
  • _type() cumulative time: reduced from 0.109s to 0.057s (47.7% faster).
  • _column_type() cumulative time: reduced from 0.129s to 0.075s (41.8% faster).
  • End-to-end table generation: ~15% faster.

Verification

  • 382/382 unit tests passed (pytest test/).
  • Zero changes to public APIs, table output, or behavior.

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.

2 participants