Skip to content

PERF: consolidate code in string search operations and speed up StringDTpe - #33546

Open
ngoldbaum wants to merge 3 commits into
numpy:mainfrom
ngoldbaum:search-perf
Open

ngoldbaum wants to merge 3 commits into
numpy:mainfrom
ngoldbaum:search-perf

Conversation

@ngoldbaum

@ngoldbaum ngoldbaum commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

PR summary

A Quansight client privately reported a slow operation on a StringDType array. Here's an example that illustrates the issue:

In [1]: import numpy as np
   ...:
   ...: short = np.full(1000, "/data/" + "x" * 16 + ".csv", dtype="T")
   ...: long = np.full(1000, "/data/" + "x" * 512 + ".csv", dtype="T")
   ...:
   ...: %timeit np.strings.startswith(short, "/data/")
   ...: %timeit np.strings.startswith(long, "/data/")
   ...: %timeit np.strings.endswith(short, ".csv")
   ...: %timeit np.strings.endswith(long, ".csv")
18.6 μs ± 21.1 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
159 μs ± 366 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
31.7 μs ± 389 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
827 μs ± 11.7 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

Both startswith and endswith should take about the same time on either a short or a long array if there is a match at the beginning or end but on current main, performance scales with the length of the strings.

I found the same problem in several np.strings functions: counting characters or continuing to search after finding a match. Skipping those scans helped StringDType the most (particularly for startswith and endswith where searching is the whole operation), and also sped up some fixed-width bytes and Unicode operations. As a bonus, sharing the search and strip code cut the implementation by more than 200 lines.

I benchmarked path manipulation and text cleaning on arrays of 1,000 strings. Benchmark code. I tried to include cases that should benefit from this and also cases that shouldn't benefit to catch regressions.

The table shows time with this patch divided by time on the parent commit. Values below 1.000 are faster (release builds, Apple M1, four paired rounds with benchx).

Operation StringDType Fixed-width Unicode Fixed-width bytes
startswith, ASCII paths 0.101 0.929 0.987
endswith, ASCII paths 0.069 1.089 1.062
startswith, non-ASCII paths 0.046 0.956 —
endswith, non-ASCII paths 0.037 1.016 —
Count path separators 0.962 0.960 0.940
Find the last path separator 0.173 0.962 0.981
Search backwards for .csv 0.299 0.811 0.848
Replace a path prefix once 0.483 0.936 0.935
Strip whitespace 0.752 1.020 —
Strip specified characters 0.770 1.035 —
Normalize CRLF line endings 0.541 0.931 —

In the cases I checked, forcing a different link order made the regressions disappear or turn into improvements.

Full benchx summary (47 cases)

I compared cdd919ae76 with 0a2e19f713 plus the local count and rfind changes, using CPython 3.14.6. I alternated which build ran first.

run-key full-followup-1796156297292110000  profile environments  baseline before  contender after  [local-only]
  before: observed env: OMP_NUM_THREADS=1, OPENBLAS_NUM_THREADS=1, VECLIB_MAXIMUM_THREADS=1
  after: observed env: OMP_NUM_THREADS=1, OPENBLAS_NUM_THREADS=1, VECLIB_MAXIMUM_THREADS=1
  differs: coordinates.environment.system.numpy.binary, coordinates.environment.system.numpy.commit, coordinates.environment.system.numpy.sha256
  caveats: baseline: dirty-benchmark-tree, dirty-subject-tree
           contender: dirty-benchmark-tree, dirty-subject-tree

REGRESSED (4)
  bench_strings.StringPathSelection.time_endswith [dtype='S'] wall-time  effect   +6.23%  noise   0.18%  rounds=4
  bench_strings.StringPathSelection.time_endswith [dtype='U'] wall-time  effect   +8.93%  noise   0.19%  rounds=4
  bench_strings.StringTextCleaning.time_strip_characters [dtype='U'] wall-time  effect   +3.53%  noise   0.14%  rounds=4
  bench_strings.StringUnicodePathSelection.time_endswith [dtype='U'] wall-time  effect   +1.58%  noise   0.09%  rounds=4

IMPROVED (33)
  bench_strings.StringEmptyPatternSearch.time_count [dtype='S'] wall-time  effect  -22.74%  noise   0.21%  rounds=4
  bench_strings.StringEmptyPatternSearch.time_endswith_bounded [dtype='S'] wall-time  effect   -8.08%  noise   0.25%  rounds=4
  bench_strings.StringEmptyPatternSearch.time_insert_separator [dtype='S'] wall-time  effect  -90.68%  noise   0.02%  rounds=4
  bench_strings.StringEmptyPatternSearch.time_insert_separator [dtype='T'] wall-time  effect  -20.50%  noise   0.32%  rounds=4
  bench_strings.StringPathSelection.time_count [dtype='S'] wall-time  effect   -6.02%  noise   0.56%  rounds=4
  bench_strings.StringPathSelection.time_endswith [dtype='T'] wall-time  effect  -93.10%  noise   0.03%  rounds=4
  bench_strings.StringPathSelection.time_find [dtype='S'] wall-time  effect   -4.75%  noise   0.21%  rounds=4
  bench_strings.StringPathSelection.time_find [dtype='T'] wall-time  effect  -77.58%  noise   0.04%  rounds=4
  bench_strings.StringPathSelection.time_find [dtype='U'] wall-time  effect   -8.56%  noise   0.07%  rounds=4
  bench_strings.StringPathSelection.time_find_missing [dtype='S'] wall-time  effect   -5.06%  noise   0.02%  rounds=4
  bench_strings.StringPathSelection.time_find_missing [dtype='T'] wall-time  effect  -89.59%  noise   0.06%  rounds=4
  bench_strings.StringPathSelection.time_find_missing [dtype='U'] wall-time  effect   -7.75%  noise   0.72%  rounds=4
  bench_strings.StringPathSelection.time_replace [dtype='T'] wall-time  effect  -23.37%  noise   0.09%  rounds=4
  bench_strings.StringPathSelection.time_replace_first [dtype='S'] wall-time  effect   -6.48%  noise   0.42%  rounds=4
  bench_strings.StringPathSelection.time_replace_first [dtype='T'] wall-time  effect  -51.71%  noise   0.03%  rounds=4
  bench_strings.StringPathSelection.time_replace_first [dtype='U'] wall-time  effect   -6.37%  noise   0.06%  rounds=4
  bench_strings.StringPathSelection.time_rfind [dtype='S'] wall-time  effect   -1.91%  noise   0.11%  rounds=4
  bench_strings.StringPathSelection.time_rfind [dtype='T'] wall-time  effect  -82.75%  noise   0.03%  rounds=4
  bench_strings.StringPathSelection.time_rfind [dtype='U'] wall-time  effect   -3.82%  noise   0.14%  rounds=4
  bench_strings.StringPathSelection.time_rfind_extension [dtype='S'] wall-time  effect  -15.16%  noise   0.16%  rounds=4
  bench_strings.StringPathSelection.time_rfind_extension [dtype='T'] wall-time  effect  -70.08%  noise   0.17%  rounds=4
  bench_strings.StringPathSelection.time_rfind_extension [dtype='U'] wall-time  effect  -18.86%  noise   0.18%  rounds=4
  bench_strings.StringPathSelection.time_startswith [dtype='S'] wall-time  effect   -1.30%  noise   0.03%  rounds=4
  bench_strings.StringPathSelection.time_startswith [dtype='T'] wall-time  effect  -89.93%  noise   0.08%  rounds=4
  bench_strings.StringPathSelection.time_startswith [dtype='U'] wall-time  effect   -7.05%  noise   0.43%  rounds=4
  bench_strings.StringTextCleaning.time_count_lines [dtype='T'] wall-time  effect   -2.93%  noise   0.04%  rounds=4
  bench_strings.StringTextCleaning.time_normalize_newlines [dtype='T'] wall-time  effect  -45.87%  noise   0.20%  rounds=4
  bench_strings.StringTextCleaning.time_normalize_newlines [dtype='U'] wall-time  effect   -6.85%  noise   0.30%  rounds=4
  bench_strings.StringTextCleaning.time_strip [dtype='T'] wall-time  effect  -24.82%  noise   1.02%  rounds=4
  bench_strings.StringTextCleaning.time_strip_characters [dtype='T'] wall-time  effect  -22.99%  noise   0.49%  rounds=4
  bench_strings.StringUnicodePathSelection.time_endswith [dtype='T'] wall-time  effect  -96.34%  noise   0.06%  rounds=4
  bench_strings.StringUnicodePathSelection.time_startswith [dtype='T'] wall-time  effect  -95.38%  noise   0.01%  rounds=4
  bench_strings.StringUnicodePathSelection.time_startswith [dtype='U'] wall-time  effect   -4.44%  noise   0.30%  rounds=4

NO CHANGE DETECTED (10)
  bench_strings.StringEmptyPatternSearch.time_count [dtype='T'] wall-time  effect   -0.88%  noise   0.28%  rounds=4
  bench_strings.StringEmptyPatternSearch.time_endswith_bounded [dtype='T'] wall-time  effect   +0.35%  noise   0.49%  rounds=4
  bench_strings.StringEmptyPatternSearch.time_rfind_bounded [dtype='S'] wall-time  effect   +0.59%  noise   0.46%  rounds=4
  bench_strings.StringEmptyPatternSearch.time_rfind_bounded [dtype='T'] wall-time  effect   -0.29%  noise   0.13%  rounds=4
  bench_strings.StringPathSelection.time_count [dtype='T'] wall-time  effect   -3.75%  noise   0.42%  rounds=4
  bench_strings.StringPathSelection.time_count [dtype='U'] wall-time  effect   -3.95%  noise   0.46%  rounds=4
  bench_strings.StringPathSelection.time_replace [dtype='S'] wall-time  effect   -2.62%  noise   0.64%  rounds=4
  bench_strings.StringPathSelection.time_replace [dtype='U'] wall-time  effect   -1.16%  noise   0.13%  rounds=4
  bench_strings.StringTextCleaning.time_count_lines [dtype='U'] wall-time  effect   -3.05%  noise   0.34%  rounds=4
  bench_strings.StringTextCleaning.time_strip [dtype='U'] wall-time  effect   +1.96%  noise   0.42%  rounds=4

AI Disclosure

I worked on this with an AI model.

@ngoldbaum ngoldbaum added this to the 2.7.0 Release milestone Dec 1, 2026
@ikrommyd

ikrommyd commented Dec 1, 2026

Copy link
Copy Markdown
Member

CI hit #33545 :)

@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.

This is really nice, thanks! I couldn't find any correctness issues, and the performance boost is big and clear so this seems ready on that front :) There are some questions and suggestions (including a couple that my agent identified) below, many take-it-or-leave-it.

Faster string searching operations
----------------------------------
`numpy.strings.startswith` and `numpy.strings.endswith` are now much faster
for `numpy.dtypes.StringDType` arrays can skip scanning the whole string when

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.

run-on here: "are now much faster for StringDType arrays can skip scanning..."

return 0;
}
}
if (!prepare_search_slice(buf1, start, end)) {

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.

The old code had a fast-path for empty needles, should we still have that (in the non-negative index path, for negative indices it's already there)? After all we don't actually run num_codepoints anymore so it could be actually faster!

Comment on lines +731 to +749
if (enc != ENCODING::UTF8) {
adjust_offsets(&start, &end, buf.num_codepoints());
if (start > end) {
return false;
}
buf.after = (buf + end).buf;
buf += start;
}
else {
if (start < 0 || end < 0) {
adjust_offsets(&start, &end, buf.num_codepoints());
}
if (start > end || start > (npy_int64)buf.buffer_width() ||
buf.advance(start) != start) {
return false;
}
}
end -= start;
return true;

@MaanasArora MaanasArora Dec 3, 2026 •

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.

I'm tempted to simplify this into stages rather than branch by encoding, something like this:

template <ENCODING enc>
static inline bool
prepare_search_slice(Buffer<enc> &buf, npy_int64 &start, npy_int64 &end)
{
    if (enc != ENCODING::UTF8 || start < 0 || end < 0) {
        adjust_offsets(&start, &end, buf.num_codepoints());
    }
    if (start > end) {
        return false;
    }

    if (enc != ENCODING::UTF8) {
        buf.after = (buf + end).buf;
        buf += start;
    }
    else if (start > (npy_int64)buf.buffer_width() ||
             buf.advance(start) != start) {
        return false;
    }

    end -= start;
    return true;
}

static inline bool
prepare_search_slice(Buffer<enc> &buf, npy_int64 &start, npy_int64 &end)
{
if (enc != ENCODING::UTF8) {

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.

A bit nitpicky, should we use constexpr here? (If we simplify as below, it can go in the second check.)

Also in any other places where enc is templated and this makes sense.

static NPY_FINLINE npy_intp
buffer_search(Buffer<enc> buf, Buffer<enc> pattern, npy_intp max_count, int mode)
{
if (enc == ENCODING::UTF32) {

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.

These branches can also be merged by typing with CodeUnit!

}
if (pattern.buffer_width() == 0) {
if ((size_t)max_count > buf.buffer_width()) {
return 1 + buf.num_codepoints();

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.

This does some validation no, otherwise it is the same as the advance below? Is this branch needed for another reason? Not sure how it affects performance (I'd guess advance is faster)!

buf3.buffer_memcpy(out, span3);
ret += span3;
out.advance_chars_or_bytes(span3);
if (has_null_padding(enc) && len3 == 1) {

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.

My agent noticed this branch is not needed!


template <ENCODING enc>
inline Buffer<enc>
operator+(Buffer<enc> lhs, npy_int64 rhs)

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.

My agent noticed this could also be simplified to use advance? (It actually suggests +=, which would be much smaller though not sure about the dependency!)

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants