Skip to content

BUG: Avoid excessive temporary memory in StringDType slice and replace - #33241

Merged
MaanasArora merged 2 commits into
numpy:mainfrom
ngoldbaum:strings-slice-replace-memory
Nov 16, 2026
Merged

MaanasArora merged 2 commits into
numpy:mainfrom
ngoldbaum:strings-slice-replace-memory

Conversation

@ngoldbaum

Copy link
Copy Markdown
Member

PR summary

Slicing a StringDType string builds a temporary array containing one pointer per character, even when selecting just one character. On a 64-bit system, this requires roughly eight bytes per character before accounting for allocation overhead.

This PR walks the string directly instead of building the temporary array. This also removes the uncaught std::bad_alloc failure caused by growing the temporary vector.

Replacing an empty pattern in a StringDType string allocates a temporary large enough to insert the replacement at every position, even with count=1. For example, prepending "prefix: " to a 1 MiB ASCII string reserves about 9 MiB for that temporary. The result grows by just eight bytes.

This PR calculates the actual result size using the replacement count and writes directly into the output when possible. The new implementation keeps a temporary only when needed to handle shared storage safely.

I refactored both operations to move the slicing and replace logic into helpers. The algorithms are completely re-written so this ends up being a clearer diff too. I think the resulting structure is clearer.

I also added a memory-limit test that exercises the string operations in the existing unary, binary, and comparison tables with a ~1 MB string operand. Each operation runs in a separate child process with a small additional virtual-memory allowance after input creation. This catches excessive peak allocations. A coverage check keeps the function tables in sync with the np.strings API. Operations with known excessive allocations through Python string methods are explicitly excluded from the memory test.

towards fixing #33240

AI Disclosure

I used an AI model to work on this.

@ngoldbaum
ngoldbaum force-pushed the strings-slice-replace-memory branch from 595fe04 to b8482ec Compare November 7, 2026 00:50

@MaanasArora MaanasArora left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Nathan, LGTM!

@MaanasArora
MaanasArora merged commit fcb01c9 into numpy:main Nov 16, 2026
100 of 102 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

00 - Bug component: numpy.strings String dtypes and functions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants