{"article":{"slug":"making-np-searchsorted-up-to-25-faster-in-numpy-2-5","title":"Making np.searchsorted up to 25× Faster in NumPy 2.5","subtitle":null,"summary":"Alejandro Candioti explains how NumPy 2.5 makes np.searchsorted up to 25 times faster by batching many binary searches so their independent memory accesses overlap, starting from a vectorized Python prototype that beat NumPy 2.4's native code, and discusses cache-friendly layouts like Eytzinger as a future direction.","content_type":"blog_post","language":"en","canonical_url":"https://blog.scientific-python.org/numpy/searchsorted/","author":{"name":"Alejandro Candioti","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Scientific Python Blog","url":"https://blog.scientific-python.org/","listing_slug":null,"listing":null},"topics":[{"name":"Python","slug":"python","url":"https://listedarticles.com/topics/python"},{"name":"Performance","slug":"performance","url":"https://listedarticles.com/topics/performance"},{"name":"Algorithms","slug":"algorithms","url":"https://listedarticles.com/topics/algorithms"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":2861,"reading_minutes":12,"published_at":"2026-09-29T00:00:00.000Z","added_at":"2026-10-11T02:08:45.069Z","updated_at":"2026-10-11T02:08:45.069Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/making-np-searchsorted-up-to-25-faster-in-numpy-2-5","markdown_url":"https://listedarticles.com/articles/making-np-searchsorted-up-to-25-faster-in-numpy-2-5.md","example":false,"citation":"Alejandro Candioti, Scientific Python Blog. \"Making np.searchsorted up to 25× Faster in NumPy 2.5.\" 29 Sept 2026. https://blog.scientific-python.org/numpy/searchsorted/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://blog.scientific-python.org/numpy/searchsorted/"},"body_markdown":"# Making np.searchsorted up to 25× Faster in NumPy 2.5\n\n[Alejandro Candioti](https://blog.scientific-python.org/authors/amcandio)\n\n September 29, 2026\n\n[#numpy](https://blog.scientific-python.org/tags/numpy)\n[#performance](https://blog.scientific-python.org/tags/performance)\n[#binary-search](https://blog.scientific-python.org/tags/binary-search)\n[#searchsorted](https://blog.scientific-python.org/tags/searchsorted)\n\n\n`np.searchsorted` is NumPy’s implementation of the binary search algorithm. This is one of the fundamental search algorithms and is used in the Python scientific ecosystem for functionality such as histogram computation and interval lookups. Any optimization benefits libraries such as SciPy and scikit-learn, as well as the broader Python scientific ecosystem.\n\nSeveral case studies, such as [Binary search variants and the effects of batching](https://curiouscoding.nl/posts/binsearch/) and [Algorithmica’s Binary Search case study](https://en.algorithmica.org/hpc/data-structures/binary-search/) explore techniques such as branch elimination, batching, and cache-friendly data layouts to binary search performance. In this post, we explore how those ideas can be expressed using NumPy’s vectorized primitives.\n\nWe will derive a vectorized formulation that outperforms NumPy 2.4’s searchsorted implementation, and then port the resulting algorithm back into NumPy. The change was included in NumPy 2.5, achieving up to a 25× speedup in our benchmarks.\n\n`searchsorted` is also part of the [Python Array API Standard](https://data-apis.org/array-api/latest/API_specification/generated/array_api.searchsorted.html#array_api.searchsorted). This allows us to compare how different array libraries implement the same operation and exploit parallelism.\n\n## Problem definition#\n\nGiven a static sorted array and a sequence of query keys, find the insertion position of each key in the array.\n\nA classic pure-Python implementation runs one binary search per key:\n\n```\ndef searchsorted_py(a, xs):\n    res = np.empty(len(xs), dtype=np.int32)\n\n    for i, x in enumerate(xs):\n        lo = 0\n        hi = len(a)\n\n        while lo < hi:\n            mid = (lo + hi) // 2\n            if a[mid] < x:\n                lo = mid + 1\n            else:\n                hi = mid\n\n        res[i] = lo\n\n    return res\n```\n\n![](/numpy/searchsorted/images/figure1-fs8.png)\n\nRunning time per query grows logarithmically as the input size grows (note the logarithmic scale of x-axis).\n\nFor benchmarking, we generated two random arrays of uniformly distributed `np.int32` integers. The keys (i.e. the elements being searched) had a fixed length of 10,000, while the length of the sorted array varied up to $2^{30}$ ($4\\ GiB$). Both keys and values arrays are contiguous in memory. Each benchmark was repeated 50 times, and we report the minimum execution time.\n\nThe benchmarks were run on a MacBook Pro with an Apple M1 Pro and 32 GB of memory. The M1 Pro has 128 KB of L1 data cache per performance core, enough to hold $2^{15}$ 32-bit integers, and a 12 MB L2 cache shared by its performance cores, enough to hold $1.5 \\* 2^{21}$ 32-bit integers.\n\n## Batching with NumPy arrays#\n\nThe baseline implementation performs one binary search per query. Each search is independent, but executed sequentially in Python. We can adapt the algorithm so multiple binary searches make progress together in batches. For that we can represent the state of all searches as arrays and update them simultaneously using vectorized operations.\n\nIn NumPy, operations on arrays are executed in compiled C++ loops. This removes Python overhead and allows the CPU to efficiently process large batches of independent work.\n\n## Let’s vectorize our binary search#\n\nTo vectorize the algorithm, we reinterpret scalar variables as array state. Instead of a single `lo` and `hi`, we maintain one value per query. In our original implementation, the state consists of `lo`, `hi`, and `res`. Since `lo` ends up containing the final result, we can focus on tracking just `lo` and `hi`.\n\nThis first vectorized implementation is a direct translation of the previous algorithm.\n\n```\ndef searchsorted_py_np(a, xs):\n    lo = np.zeros(xs.shape, dtype=np.int32)\n    hi = np.full(xs.shape, len(a), dtype=np.int32)\n\n    while True:\n        # True for each element position where lo_i < hi_i\n        active = lo < hi\n        if not np.any(active):\n            # this is basically `while lo < hi:` in the pure-Python version\n            break\n\n        mid = (lo + hi) // 2\n\n        # only index those entries where active is true, so we don't modify already computed positions\n        mid_a = mid[active]\n        xs_a = xs[active]\n\n        mask = a[mid_a] < xs_a\n\n        lo[active] = np.where(mask, mid_a + 1, lo[active])\n        hi[active] = np.where(mask, hi[active], mid_a)\n\n    return lo\n```\n\n![](/numpy/searchsorted/images/figure2-fs8.png)\n\nIn this implementation, different queries can shrink their search intervals at different rates, so they may require different numbers of iterations to converge.\n\nFor example, consider searching for the keys `[-1, 2]` in the array `[0, 1]`. For the query `2`, the first iteration computes `mid = 1` and sets `lo = mid + 1 = 2`, so the interval becomes `[2, 2)` and the search converges in one step. For the query `-1`, the update instead sets `hi = mid = 1`, leaving the interval `[0, 1)` after the first step. This requires an additional iteration to collapse the interval to `[0, 0)`.\n\nBecause the searches can converge at different times, we need to keep track of which queries are still active. The active mask identifies the queries whose search intervals have not yet converged, allowing us to update only those queries.\n\n### Making all searches take the same number of steps#\n\nThe important observation is that binary search does not actually need to terminate independently for each key. We can tweak each iteration update in a way that, once a search has converged, subsequent iterations can leave its interval unchanged.\n\nWe maintain the invariant that the insertion position lies in `[lo, hi)`. At each iteration, every interval is reduced to roughly half its previous size. After `np.ceil(np.log2(n))` iterations, every interval has collapsed to a single position.\n\nFor simplicity, this implementation assumes `a` is non-empty.\n\n```\ndef searchsorted_py_np_fixed(a, xs):\n    n = len(a)\n    lo = np.zeros(xs.shape, dtype=np.int32)\n    hi = np.full(xs.shape, n, dtype=np.int32)\n\n    for _ in range(int(np.ceil(np.log2(n)))):\n        mid = (lo + hi) // 2\n        go_left = xs <= a[mid]\n\n        # for each position i:\n        # if go_left_i is True, we keep the `lo_i` value and `hi_i` is updated to `mid_i`\n        # if go_left_i is False, we keep the `hi_i` value and `lo_i` is updated to `mid_i`\n        lo = np.where(go_left, lo, mid)\n        hi = np.where(go_left, mid, hi)\n\n    return hi\n```\n\nRemoving the `active` tracker makes it up to 2× faster.\n\n![](/numpy/searchsorted/images/figure3-fs8.png)\n\nA similar formulation can already be found in the Python ecosystem. For example, [JAX’s scan-based implementation](https://github.com/jax-ml/jax/blob/a6e4a8b95a731269bdf23e5b3e30da2f8494bb28/jax/_src/numpy/hijax.py#L330)\n\n```\n...\n\ndef body_fun(state, _):\n    low, high = state\n    mid = low + (high - low) // 2  # use this form to avoid overflow\n    go_left = op(query, sorted_arr[mid])\n    return (lax.select(go_left, low, mid), lax.select(go_left, mid, high)), ()\n\nn_levels = int(np.ceil(np.log2(n + 1)))\n...\n```\n\n### Can NumPy beat NumPy?#\n\nLet’s compare the performance of this vectorized implementation with NumPy’s native `searchsorted` (using NumPy 2.4).\n\n![](/numpy/searchsorted/images/figure4-fs8.png)\n\nOur vectorized Python implementation can be an order of magnitude faster than the native one for inputs with several keys. To understand why, let’s take a look at `NumPy 2.4` implementation:\n\n```\ntemplate <class Tag, side_t side>\nstatic void\nbinsearch(const char *arr, const char *key, char *ret, npy_intp arr_len,\n          npy_intp key_len, npy_intp arr_str, npy_intp key_str,\n          npy_intp ret_str, PyArrayObject *)\n{\n    using T = typename Tag::type;\n    auto cmp = side_to_cmp<Tag, side>::value;\n    npy_intp min_idx = 0;\n    npy_intp max_idx = arr_len;\n    T last_key_val;\n\n    if (key_len == 0) {\n        return;\n    }\n    last_key_val = *(const T *)key;\n\n    for (; key_len > 0; key_len--, key += key_str, ret += ret_str) {\n        const T key_val = *(const T *)key;\n        /*\n         * Updating only one of the indices based on the previous key\n         * gives the search a big boost when keys are sorted, but slightly\n         * slows down things for purely random ones.\n         */\n        if (cmp(last_key_val, key_val)) {\n            max_idx = arr_len;\n        }\n        else {\n            min_idx = 0;\n            max_idx = (max_idx < arr_len) ? (max_idx + 1) : arr_len;\n        }\n\n        last_key_val = key_val;\n\n        while (min_idx < max_idx) {\n            const npy_intp mid_idx = min_idx + ((max_idx - min_idx) >> 1);\n            const T mid_val = *(const T *)(arr + mid_idx * arr_str);\n            if (cmp(mid_val, key_val)) {\n                min_idx = mid_idx + 1;\n            }\n            else {\n                max_idx = mid_idx;\n            }\n        }\n        *(npy_intp *)ret = min_idx;\n    }\n}\n```\n\nIgnoring the pointer arithmetic details, the core algorithm is a classic binary search executed independently for each key. There is also an optimization that reuses previous search bounds when the input keys are sorted.\n\nThis implementation performs one binary search per key, where each search is a fully sequential process. Each iteration of the binary search depends on the result of the previous one (the midpoint determines which part of the array is inspected next). This creates a dependency chain within each search: the next memory access depends on the result of the previous comparison.\n\nFor large arrays, binary-search reads also tend to be cache-unfriendly, since each step may require a read from a different cache line. Cache misses have a greater impact on the sequential implementation because each step may stall waiting for the previous memory access to complete.\n\nThe vectorized implementation performs the same logical step across all queries at once (all queries advance at each step together). **With multiple independent searches, the CPU can have several memory accesses in flight at once.** This aligns with the observed running time once the array size exceeds the L1 and L2 cache sizes.\n\n### Can we optimize NumPy?#\n\nThe previous vectorized implementation maintains two arrays, `lo` and `hi`, to represent the search interval for each query. If we were to port this exact implementation into NumPy natively, it would require using $O(K)$ additional memory where `K` is the number of queries. Even though this approach is potentially faster, this is unacceptable for memory-sensitive workloads.\n\nTo reduce the state required, we can reformulate binary search in terms of interval boundaries. Instead of tracking both `lo` and `hi` for each query, we describe each interval using its left boundary and its length.\n\nThe key observation is that if we structure the algorithm so that all queries shrink their intervals by the same amount at each iteration, then every interval has the same length at each iteration. This means we do not need to store a separate `hi` per query: it can be reconstructed from a single array `lo` and a global length. Note that this still needs $O(K)$ space for the output, but it requires only $O(1)$ memory beyond that output.\n\nThis gives us the following Python implementation:\n\n```\ndef searchsorted_py_np_fast_where(arr, keys):\n    K = keys.shape[0]\n    length = arr.shape[0]\n\n    base = np.zeros(K, dtype=np.intp)\n\n    # Invariant: the insertion index lies in [base, base + length]\n    while length > 1:\n        half = length >> 1\n        mid = base + half\n        base = np.where(keys > arr[mid], mid, base)\n        length -= half\n\n    # Final step: result is either base and base + 1\n    base = np.where(keys > arr[base], base + 1, base)\n\n    return base\n```\n\nOnly a single array `base` is needed to store the per-query state, while length is shared across all queries. The output is written directly into base, so no additional state array is required. This implementation still requires allocating a temporary `mid` to hold the midpoints, but this can be avoided in the C++ port.\n\nThis formulation is closely related to the branchless binary search approach discussed in [Algorithmica’s case study](https://en.algorithmica.org/hpc/data-structures/binary-search/#removing-branches). In the formulation we use, the invariant range is `[base, base + length]`. Therefore a final step is required when `length = 1` to resolve whether the insertion point falls to the left or right of `base`.\n\nThe reformulated implementation is significantly faster:\n\n![](/numpy/searchsorted/images/figure6-fs8.png)\n\n### Porting it into C++#\n\nThe performance results show the benefit of reducing the per-query state. We can now translate it almost directly to C++ with $O(1)$ additional memory.\n\n```\ntemplate <class Tag, side_t side>\nstatic void\nbinsearch(const char *arr, const char *key, char *ret, npy_intp arr_len,\n          npy_intp key_len, npy_intp arr_str, npy_intp key_str,\n          npy_intp ret_str, PyArrayObject *)\n{\n    using T = typename Tag::type;\n    auto cmp = side_to_cmp<Tag, side>::value;\n\n    // If the array length is 0 we return all 0s\n    if (arr_len <= 0) {\n        for (npy_intp i = 0; i < key_len; ++i) {\n            *(npy_intp *)(ret + i * ret_str) = 0;\n        }\n        return;\n    }\n\n    /*\n    base = np.zeros(K, dtype=np.intp)\n\n    We unroll the first iteration for the following reasons:\n        1. ret is not initialized with the bases, so we save |keys| writes\n        by not having to initialize it with 0s.\n        2. By assuming the initial base for every key is 0, we also save\n        |keys| reads.\n        3. In the first iteration, all elements are compared against the\n        median. So we can store it in a variable and use it for all keys.\n\n    This initial block replaces the initialization loop that is used for the\n    arr_len==0 case. Note that when arr_len = 1, then half is 0 so the\n    following block initializes the array as with 0s.\n    */\n    npy_intp interval_length = arr_len;\n    npy_intp half = interval_length >> 1;\n    interval_length -= half; // length -> ceil(length / 2)\n\n    npy_intp base = 0;\n    const T mid_val = *(const T *)(arr + (base + half) * arr_str);\n\n    for (npy_intp i = 0; i < key_len; ++i) {\n        const T key_val = *(const T *)(key + i * key_str);\n        *(npy_intp *)(ret + i * ret_str) = cmp(mid_val, key_val) * half;\n    }\n\n    /*\n        while length > 1:\n            half = length >> 1\n            length -= half\n            mid = base + half\n            base = np.where(keys > arr[mid], mid, base)\n    */\n    while (interval_length > 1) {\n        npy_intp half = interval_length >> 1;\n        interval_length -= half;\n\n        for (npy_intp i = 0; i < key_len; ++i) {\n            npy_intp &base = *(npy_intp *)(ret + i * ret_str);\n            const T mid_val = *(const T *)(arr + (base + half) * arr_str);\n            const T key_val = *(const T *)(key + i * key_str);\n            base += cmp(mid_val, key_val) * half;\n        }\n    }\n\n    // base = np.where(keys > arr[base], base + 1, base)\n    for (npy_intp i = 0; i < key_len; ++i) {\n        npy_intp &base = *(npy_intp *)(ret + i * ret_str);\n        const T key_val = *(const T *)(key + i * key_str);\n        base += cmp(*(const T *)(arr + base * arr_str), key_val);\n    }\n}\n```\n\nNote that we exploited a property of the first iteration of the binary search. Because the initial value of every result entry is implicitly zero, we can skip writing and reading those values during the first iteration. Moreover, in the first iteration all elements are compared against the same median, so we can read its value once instead of `K` times.\n\nThis implementation was ported directly into NumPy as part of PR [#30517](https://github.com/numpy/numpy/pull/30517), which was included in the [2.5 release](https://numpy.org/devdocs/release/2.5.0-notes.html#improved-performance-of-numpy-searchsorted). Now let’s do a final comparison between NumPy 2.4 and 2.5, and our vectorized Python implementation:\n\n![](/numpy/searchsorted/images/figure7-fs8.png)\n\nThe native 2.5 version is up to 25× faster than NumPy 2.4’s implementation in our benchmarks. Compared with the vectorized Python implementation, the C++ implementation can be up to 2× as fast for smaller arrays. This difference becomes less significant as the array size grows. There is also a memory advantage over the vectorized Python implementation: the Python implementation requires additional arrays to store the search state (`low` and `mid`, or `base` and `base + length`), whereas the C++ implementation keeps length as a scalar. As a result, the C++ implementation uses only $O(1)$ additional memory, while the NumPy formulation requires memory proportional to the number of queries.\n\n### Ecosystem Comparison#\n\nWe can compare our optimized NumPy 2.5 against other libraries in the ecosystem. For this experiment, we selected the Python libraries JAX, TensorFlow, and PyTorch.\n\nTensorFlow and PyTorch follow a different approach from JAX and NumPy. While JAX and NumPy leverage vectorized/batched operations to hide memory latency, TensorFlow and PyTorch parallelize independent searches across CPU threads. Search keys are partitioned into batches that are processed by different threads. For more details, see the [PyTorch](https://github.com/pytorch/pytorch/blob/b1bb860d3c812371b89a9725407230216e7369b5/aten/src/ATen/native/Bucketization.cpp#L88) and [TensorFlow](https://github.com/tensorflow/tensorflow/blob/bb8d3f2443d70ec8c2aae1288fbf5782c771aa60/tensorflow/core/kernels/searchsorted_op.cc#L67) implementations.\n\nIn the benchmarks, we limited parallelism to 8 cores and we increased the number of query keys from 10,000 to 20,000. This gives the multithreaded implementations enough independent work to amortize thread-scheduling overhead.\n\n![](/numpy/searchsorted/images/figure8-fs8.png)\n\nThe benchmark shows that NumPy is competitive with the selected libraries in our benchmarks. All implementations exhibit similar behavior once the search array grows beyond the CPU cache.\n\nIf we disable multithreading, the performance of PyTorch and TensorFlow degrades, and both exhibit a similar trend to NumPy 2.4’s implementation. Once the search array grows beyond the CPU cache, the cost of memory accesses dominates.\n\n![](/numpy/searchsorted/images/figure9-fs8.png)\n\nIt would be worth benchmarking whether both techniques could be combined: batching binary searches within each thread. However, once the memory subsystem becomes saturated, additional cores can compete for the same memory bandwidth. At that point, improving the memory access patterns may be a more promising direction, for example by using a different layout such as the Eytzinger layout (discussed in detail in the [Algorithmica book](https://en.algorithmica.org/hpc/data-structures/binary-search/#eytzinger-layout)).\n\n### Conclusion#\n\nWe made `np.searchsorted` up to 25x faster in our benchmarks. Given NumPy’s reach in the Python ecosystem, this optimization will benefit several libraries that depend on it. Other libraries in the Python ecosystem with their own binary search implementation may also benefit from adopting similar batching techniques.\n\nInterestingly, we used NumPy array primitives to derive an initial Python implementation that outperformed NumPy 2.4’s implementation. This shows how powerful NumPy’s array primitives can be for implementing highly performant algorithms. **A vectorized NumPy implementation in Python can outperform a scalar native implementation by exploiting independent work**.\n\nCache-friendly layouts such as the Eytzinger layout are another interesting direction for making `searchsorted` faster. It would be interesting to explore whether the array API could expose such layouts through an interface like `searchsorted(arr, keys, layout=\"eytzinger\")`, although this would require carefully defining the API semantics since the Eytzinger representation is not sorted.\n","body_html":"<h1 id=\"making-np-searchsorted-up-to-25-faster-in-numpy-2-5\">Making np.searchsorted up to 25× Faster in NumPy 2.5</h1>\n<p><a href=\"https://blog.scientific-python.org/authors/amcandio\" rel=\"nofollow ugc noopener\">Alejandro Candioti</a></p>\n<p> September 29, 2026</p>\n<p><a href=\"https://blog.scientific-python.org/tags/numpy\" rel=\"nofollow ugc noopener\">#numpy</a>\n<a href=\"https://blog.scientific-python.org/tags/performance\" rel=\"nofollow ugc noopener\">#performance</a>\n<a href=\"https://blog.scientific-python.org/tags/binary-search\" rel=\"nofollow ugc noopener\">#binary-search</a>\n<a href=\"https://blog.scientific-python.org/tags/searchsorted\" rel=\"nofollow ugc noopener\">#searchsorted</a></p>\n<p><code>np.searchsorted</code> is NumPy’s implementation of the binary search algorithm. This is one of the fundamental search algorithms and is used in the Python scientific ecosystem for functionality such as histogram computation and interval lookups. Any optimization benefits libraries such as SciPy and scikit-learn, as well as the broader Python scientific ecosystem.</p>\n<p>Several case studies, such as <a href=\"https://curiouscoding.nl/posts/binsearch/\" rel=\"nofollow ugc noopener\">Binary search variants and the effects of batching</a> and <a href=\"https://en.algorithmica.org/hpc/data-structures/binary-search/\" rel=\"nofollow ugc noopener\">Algorithmica’s Binary Search case study</a> explore techniques such as branch elimination, batching, and cache-friendly data layouts to binary search performance. In this post, we explore how those ideas can be expressed using NumPy’s vectorized primitives.</p>\n<p>We will derive a vectorized formulation that outperforms NumPy 2.4’s searchsorted implementation, and then port the resulting algorithm back into NumPy. The change was included in NumPy 2.5, achieving up to a 25× speedup in our benchmarks.</p>\n<p><code>searchsorted</code> is also part of the <a href=\"https://data-apis.org/array-api/latest/API_specification/generated/array_api.searchsorted.html#array_api.searchsorted\" rel=\"nofollow ugc noopener\">Python Array API Standard</a>. This allows us to compare how different array libraries implement the same operation and exploit parallelism.</p>\n<h2 id=\"problem-definition\">Problem definition</h2>\n<p>Given a static sorted array and a sequence of query keys, find the insertion position of each key in the array.</p>\n<p>A classic pure-Python implementation runs one binary search per key:</p>\n<pre><code>def searchsorted_py(a, xs):\n    res = np.empty(len(xs), dtype=np.int32)\n\n    for i, x in enumerate(xs):\n        lo = 0\n        hi = len(a)\n\n        while lo &lt; hi:\n            mid = (lo + hi) // 2\n            if a[mid] &lt; x:\n                lo = mid + 1\n            else:\n                hi = mid\n\n        res[i] = lo\n\n    return res</code></pre>\n<p></p>\n<p>Running time per query grows logarithmically as the input size grows (note the logarithmic scale of x-axis).</p>\n<p>For benchmarking, we generated two random arrays of uniformly distributed <code>np.int32</code> integers. The keys (i.e. the elements being searched) had a fixed length of 10,000, while the length of the sorted array varied up to $2^{30}$ ($4\\ GiB$). Both keys and values arrays are contiguous in memory. Each benchmark was repeated 50 times, and we report the minimum execution time.</p>\n<p>The benchmarks were run on a MacBook Pro with an Apple M1 Pro and 32 GB of memory. The M1 Pro has 128 KB of L1 data cache per performance core, enough to hold $2^{15}$ 32-bit integers, and a 12 MB L2 cache shared by its performance cores, enough to hold $1.5 * 2^{21}$ 32-bit integers.</p>\n<h2 id=\"batching-with-numpy-arrays\">Batching with NumPy arrays</h2>\n<p>The baseline implementation performs one binary search per query. Each search is independent, but executed sequentially in Python. We can adapt the algorithm so multiple binary searches make progress together in batches. For that we can represent the state of all searches as arrays and update them simultaneously using vectorized operations.</p>\n<p>In NumPy, operations on arrays are executed in compiled C++ loops. This removes Python overhead and allows the CPU to efficiently process large batches of independent work.</p>\n<h2 id=\"let-s-vectorize-our-binary-search\">Let’s vectorize our binary search</h2>\n<p>To vectorize the algorithm, we reinterpret scalar variables as array state. Instead of a single <code>lo</code> and <code>hi</code>, we maintain one value per query. In our original implementation, the state consists of <code>lo</code>, <code>hi</code>, and <code>res</code>. Since <code>lo</code> ends up containing the final result, we can focus on tracking just <code>lo</code> and <code>hi</code>.</p>\n<p>This first vectorized implementation is a direct translation of the previous algorithm.</p>\n<pre><code>def searchsorted_py_np(a, xs):\n    lo = np.zeros(xs.shape, dtype=np.int32)\n    hi = np.full(xs.shape, len(a), dtype=np.int32)\n\n    while True:\n        # True for each element position where lo_i &lt; hi_i\n        active = lo &lt; hi\n        if not np.any(active):\n            # this is basically `while lo &lt; hi:` in the pure-Python version\n            break\n\n        mid = (lo + hi) // 2\n\n        # only index those entries where active is true, so we don&#39;t modify already computed positions\n        mid_a = mid[active]\n        xs_a = xs[active]\n\n        mask = a[mid_a] &lt; xs_a\n\n        lo[active] = np.where(mask, mid_a + 1, lo[active])\n        hi[active] = np.where(mask, hi[active], mid_a)\n\n    return lo</code></pre>\n<p></p>\n<p>In this implementation, different queries can shrink their search intervals at different rates, so they may require different numbers of iterations to converge.</p>\n<p>For example, consider searching for the keys <code>[-1, 2]</code> in the array <code>[0, 1]</code>. For the query <code>2</code>, the first iteration computes <code>mid = 1</code> and sets <code>lo = mid + 1 = 2</code>, so the interval becomes <code>[2, 2)</code> and the search converges in one step. For the query <code>-1</code>, the update instead sets <code>hi = mid = 1</code>, leaving the interval <code>[0, 1)</code> after the first step. This requires an additional iteration to collapse the interval to <code>[0, 0)</code>.</p>\n<p>Because the searches can converge at different times, we need to keep track of which queries are still active. The active mask identifies the queries whose search intervals have not yet converged, allowing us to update only those queries.</p>\n<h3 id=\"making-all-searches-take-the-same-number-of-steps\">Making all searches take the same number of steps</h3>\n<p>The important observation is that binary search does not actually need to terminate independently for each key. We can tweak each iteration update in a way that, once a search has converged, subsequent iterations can leave its interval unchanged.</p>\n<p>We maintain the invariant that the insertion position lies in <code>[lo, hi)</code>. At each iteration, every interval is reduced to roughly half its previous size. After <code>np.ceil(np.log2(n))</code> iterations, every interval has collapsed to a single position.</p>\n<p>For simplicity, this implementation assumes <code>a</code> is non-empty.</p>\n<pre><code>def searchsorted_py_np_fixed(a, xs):\n    n = len(a)\n    lo = np.zeros(xs.shape, dtype=np.int32)\n    hi = np.full(xs.shape, n, dtype=np.int32)\n\n    for _ in range(int(np.ceil(np.log2(n)))):\n        mid = (lo + hi) // 2\n        go_left = xs &lt;= a[mid]\n\n        # for each position i:\n        # if go_left_i is True, we keep the `lo_i` value and `hi_i` is updated to `mid_i`\n        # if go_left_i is False, we keep the `hi_i` value and `lo_i` is updated to `mid_i`\n        lo = np.where(go_left, lo, mid)\n        hi = np.where(go_left, mid, hi)\n\n    return hi</code></pre>\n<p>Removing the <code>active</code> tracker makes it up to 2× faster.</p>\n<p></p>\n<p>A similar formulation can already be found in the Python ecosystem. For example, <a href=\"https://github.com/jax-ml/jax/blob/a6e4a8b95a731269bdf23e5b3e30da2f8494bb28/jax/_src/numpy/hijax.py#L330\" rel=\"nofollow ugc noopener\">JAX’s scan-based implementation</a></p>\n<pre><code>...\n\ndef body_fun(state, _):\n    low, high = state\n    mid = low + (high - low) // 2  # use this form to avoid overflow\n    go_left = op(query, sorted_arr[mid])\n    return (lax.select(go_left, low, mid), lax.select(go_left, mid, high)), ()\n\nn_levels = int(np.ceil(np.log2(n + 1)))\n...</code></pre>\n<h3 id=\"can-numpy-beat-numpy\">Can NumPy beat NumPy?</h3>\n<p>Let’s compare the performance of this vectorized implementation with NumPy’s native <code>searchsorted</code> (using NumPy 2.4).</p>\n<p></p>\n<p>Our vectorized Python implementation can be an order of magnitude faster than the native one for inputs with several keys. To understand why, let’s take a look at <code>NumPy 2.4</code> implementation:</p>\n<pre><code>template &lt;class Tag, side_t side&gt;\nstatic void\nbinsearch(const char *arr, const char *key, char *ret, npy_intp arr_len,\n          npy_intp key_len, npy_intp arr_str, npy_intp key_str,\n          npy_intp ret_str, PyArrayObject *)\n{\n    using T = typename Tag::type;\n    auto cmp = side_to_cmp&lt;Tag, side&gt;::value;\n    npy_intp min_idx = 0;\n    npy_intp max_idx = arr_len;\n    T last_key_val;\n\n    if (key_len == 0) {\n        return;\n    }\n    last_key_val = *(const T *)key;\n\n    for (; key_len &gt; 0; key_len--, key += key_str, ret += ret_str) {\n        const T key_val = *(const T *)key;\n        /*\n         * Updating only one of the indices based on the previous key\n         * gives the search a big boost when keys are sorted, but slightly\n         * slows down things for purely random ones.\n         */\n        if (cmp(last_key_val, key_val)) {\n            max_idx = arr_len;\n        }\n        else {\n            min_idx = 0;\n            max_idx = (max_idx &lt; arr_len) ? (max_idx + 1) : arr_len;\n        }\n\n        last_key_val = key_val;\n\n        while (min_idx &lt; max_idx) {\n            const npy_intp mid_idx = min_idx + ((max_idx - min_idx) &gt;&gt; 1);\n            const T mid_val = *(const T *)(arr + mid_idx * arr_str);\n            if (cmp(mid_val, key_val)) {\n                min_idx = mid_idx + 1;\n            }\n            else {\n                max_idx = mid_idx;\n            }\n        }\n        *(npy_intp *)ret = min_idx;\n    }\n}</code></pre>\n<p>Ignoring the pointer arithmetic details, the core algorithm is a classic binary search executed independently for each key. There is also an optimization that reuses previous search bounds when the input keys are sorted.</p>\n<p>This implementation performs one binary search per key, where each search is a fully sequential process. Each iteration of the binary search depends on the result of the previous one (the midpoint determines which part of the array is inspected next). This creates a dependency chain within each search: the next memory access depends on the result of the previous comparison.</p>\n<p>For large arrays, binary-search reads also tend to be cache-unfriendly, since each step may require a read from a different cache line. Cache misses have a greater impact on the sequential implementation because each step may stall waiting for the previous memory access to complete.</p>\n<p>The vectorized implementation performs the same logical step across all queries at once (all queries advance at each step together). <strong>With multiple independent searches, the CPU can have several memory accesses in flight at once.</strong> This aligns with the observed running time once the array size exceeds the L1 and L2 cache sizes.</p>\n<h3 id=\"can-we-optimize-numpy\">Can we optimize NumPy?</h3>\n<p>The previous vectorized implementation maintains two arrays, <code>lo</code> and <code>hi</code>, to represent the search interval for each query. If we were to port this exact implementation into NumPy natively, it would require using $O(K)$ additional memory where <code>K</code> is the number of queries. Even though this approach is potentially faster, this is unacceptable for memory-sensitive workloads.</p>\n<p>To reduce the state required, we can reformulate binary search in terms of interval boundaries. Instead of tracking both <code>lo</code> and <code>hi</code> for each query, we describe each interval using its left boundary and its length.</p>\n<p>The key observation is that if we structure the algorithm so that all queries shrink their intervals by the same amount at each iteration, then every interval has the same length at each iteration. This means we do not need to store a separate <code>hi</code> per query: it can be reconstructed from a single array <code>lo</code> and a global length. Note that this still needs $O(K)$ space for the output, but it requires only $O(1)$ memory beyond that output.</p>\n<p>This gives us the following Python implementation:</p>\n<pre><code>def searchsorted_py_np_fast_where(arr, keys):\n    K = keys.shape[0]\n    length = arr.shape[0]\n\n    base = np.zeros(K, dtype=np.intp)\n\n    # Invariant: the insertion index lies in [base, base + length]\n    while length &gt; 1:\n        half = length &gt;&gt; 1\n        mid = base + half\n        base = np.where(keys &gt; arr[mid], mid, base)\n        length -= half\n\n    # Final step: result is either base and base + 1\n    base = np.where(keys &gt; arr[base], base + 1, base)\n\n    return base</code></pre>\n<p>Only a single array <code>base</code> is needed to store the per-query state, while length is shared across all queries. The output is written directly into base, so no additional state array is required. This implementation still requires allocating a temporary <code>mid</code> to hold the midpoints, but this can be avoided in the C++ port.</p>\n<p>This formulation is closely related to the branchless binary search approach discussed in <a href=\"https://en.algorithmica.org/hpc/data-structures/binary-search/#removing-branches\" rel=\"nofollow ugc noopener\">Algorithmica’s case study</a>. In the formulation we use, the invariant range is <code>[base, base + length]</code>. Therefore a final step is required when <code>length = 1</code> to resolve whether the insertion point falls to the left or right of <code>base</code>.</p>\n<p>The reformulated implementation is significantly faster:</p>\n<p></p>\n<h3 id=\"porting-it-into-c\">Porting it into C++</h3>\n<p>The performance results show the benefit of reducing the per-query state. We can now translate it almost directly to C++ with $O(1)$ additional memory.</p>\n<pre><code>template &lt;class Tag, side_t side&gt;\nstatic void\nbinsearch(const char *arr, const char *key, char *ret, npy_intp arr_len,\n          npy_intp key_len, npy_intp arr_str, npy_intp key_str,\n          npy_intp ret_str, PyArrayObject *)\n{\n    using T = typename Tag::type;\n    auto cmp = side_to_cmp&lt;Tag, side&gt;::value;\n\n    // If the array length is 0 we return all 0s\n    if (arr_len &lt;= 0) {\n        for (npy_intp i = 0; i &lt; key_len; ++i) {\n            *(npy_intp *)(ret + i * ret_str) = 0;\n        }\n        return;\n    }\n\n    /*\n    base = np.zeros(K, dtype=np.intp)\n\n    We unroll the first iteration for the following reasons:\n        1. ret is not initialized with the bases, so we save |keys| writes\n        by not having to initialize it with 0s.\n        2. By assuming the initial base for every key is 0, we also save\n        |keys| reads.\n        3. In the first iteration, all elements are compared against the\n        median. So we can store it in a variable and use it for all keys.\n\n    This initial block replaces the initialization loop that is used for the\n    arr_len==0 case. Note that when arr_len = 1, then half is 0 so the\n    following block initializes the array as with 0s.\n    */\n    npy_intp interval_length = arr_len;\n    npy_intp half = interval_length &gt;&gt; 1;\n    interval_length -= half; // length -&gt; ceil(length / 2)\n\n    npy_intp base = 0;\n    const T mid_val = *(const T *)(arr + (base + half) * arr_str);\n\n    for (npy_intp i = 0; i &lt; key_len; ++i) {\n        const T key_val = *(const T *)(key + i * key_str);\n        *(npy_intp *)(ret + i * ret_str) = cmp(mid_val, key_val) * half;\n    }\n\n    /*\n        while length &gt; 1:\n            half = length &gt;&gt; 1\n            length -= half\n            mid = base + half\n            base = np.where(keys &gt; arr[mid], mid, base)\n    */\n    while (interval_length &gt; 1) {\n        npy_intp half = interval_length &gt;&gt; 1;\n        interval_length -= half;\n\n        for (npy_intp i = 0; i &lt; key_len; ++i) {\n            npy_intp &amp;base = *(npy_intp *)(ret + i * ret_str);\n            const T mid_val = *(const T *)(arr + (base + half) * arr_str);\n            const T key_val = *(const T *)(key + i * key_str);\n            base += cmp(mid_val, key_val) * half;\n        }\n    }\n\n    // base = np.where(keys &gt; arr[base], base + 1, base)\n    for (npy_intp i = 0; i &lt; key_len; ++i) {\n        npy_intp &amp;base = *(npy_intp *)(ret + i * ret_str);\n        const T key_val = *(const T *)(key + i * key_str);\n        base += cmp(*(const T *)(arr + base * arr_str), key_val);\n    }\n}</code></pre>\n<p>Note that we exploited a property of the first iteration of the binary search. Because the initial value of every result entry is implicitly zero, we can skip writing and reading those values during the first iteration. Moreover, in the first iteration all elements are compared against the same median, so we can read its value once instead of <code>K</code> times.</p>\n<p>This implementation was ported directly into NumPy as part of PR <a href=\"https://github.com/numpy/numpy/pull/30517\" rel=\"nofollow ugc noopener\">#30517</a>, which was included in the <a href=\"https://numpy.org/devdocs/release/2.5.0-notes.html#improved-performance-of-numpy-searchsorted\" rel=\"nofollow ugc noopener\">2.5 release</a>. Now let’s do a final comparison between NumPy 2.4 and 2.5, and our vectorized Python implementation:</p>\n<p></p>\n<p>The native 2.5 version is up to 25× faster than NumPy 2.4’s implementation in our benchmarks. Compared with the vectorized Python implementation, the C++ implementation can be up to 2× as fast for smaller arrays. This difference becomes less significant as the array size grows. There is also a memory advantage over the vectorized Python implementation: the Python implementation requires additional arrays to store the search state (<code>low</code> and <code>mid</code>, or <code>base</code> and <code>base + length</code>), whereas the C++ implementation keeps length as a scalar. As a result, the C++ implementation uses only $O(1)$ additional memory, while the NumPy formulation requires memory proportional to the number of queries.</p>\n<h3 id=\"ecosystem-comparison\">Ecosystem Comparison</h3>\n<p>We can compare our optimized NumPy 2.5 against other libraries in the ecosystem. For this experiment, we selected the Python libraries JAX, TensorFlow, and PyTorch.</p>\n<p>TensorFlow and PyTorch follow a different approach from JAX and NumPy. While JAX and NumPy leverage vectorized/batched operations to hide memory latency, TensorFlow and PyTorch parallelize independent searches across CPU threads. Search keys are partitioned into batches that are processed by different threads. For more details, see the <a href=\"https://github.com/pytorch/pytorch/blob/b1bb860d3c812371b89a9725407230216e7369b5/aten/src/ATen/native/Bucketization.cpp#L88\" rel=\"nofollow ugc noopener\">PyTorch</a> and <a href=\"https://github.com/tensorflow/tensorflow/blob/bb8d3f2443d70ec8c2aae1288fbf5782c771aa60/tensorflow/core/kernels/searchsorted_op.cc#L67\" rel=\"nofollow ugc noopener\">TensorFlow</a> implementations.</p>\n<p>In the benchmarks, we limited parallelism to 8 cores and we increased the number of query keys from 10,000 to 20,000. This gives the multithreaded implementations enough independent work to amortize thread-scheduling overhead.</p>\n<p></p>\n<p>The benchmark shows that NumPy is competitive with the selected libraries in our benchmarks. All implementations exhibit similar behavior once the search array grows beyond the CPU cache.</p>\n<p>If we disable multithreading, the performance of PyTorch and TensorFlow degrades, and both exhibit a similar trend to NumPy 2.4’s implementation. Once the search array grows beyond the CPU cache, the cost of memory accesses dominates.</p>\n<p></p>\n<p>It would be worth benchmarking whether both techniques could be combined: batching binary searches within each thread. However, once the memory subsystem becomes saturated, additional cores can compete for the same memory bandwidth. At that point, improving the memory access patterns may be a more promising direction, for example by using a different layout such as the Eytzinger layout (discussed in detail in the <a href=\"https://en.algorithmica.org/hpc/data-structures/binary-search/#eytzinger-layout\" rel=\"nofollow ugc noopener\">Algorithmica book</a>).</p>\n<h3 id=\"conclusion\">Conclusion</h3>\n<p>We made <code>np.searchsorted</code> up to 25x faster in our benchmarks. Given NumPy’s reach in the Python ecosystem, this optimization will benefit several libraries that depend on it. Other libraries in the Python ecosystem with their own binary search implementation may also benefit from adopting similar batching techniques.</p>\n<p>Interestingly, we used NumPy array primitives to derive an initial Python implementation that outperformed NumPy 2.4’s implementation. This shows how powerful NumPy’s array primitives can be for implementing highly performant algorithms. <strong>A vectorized NumPy implementation in Python can outperform a scalar native implementation by exploiting independent work</strong>.</p>\n<p>Cache-friendly layouts such as the Eytzinger layout are another interesting direction for making <code>searchsorted</code> faster. It would be interesting to explore whether the array API could expose such layouts through an interface like <code>searchsorted(arr, keys, layout=&quot;eytzinger&quot;)</code>, although this would require carefully defining the API semantics since the Eytzinger representation is not sorted.</p>","headings":[{"level":1,"text":"Making np.searchsorted up to 25× Faster in NumPy 2.5","id":"making-np-searchsorted-up-to-25-faster-in-numpy-2-5"},{"level":2,"text":"Problem definition","id":"problem-definition"},{"level":2,"text":"Batching with NumPy arrays","id":"batching-with-numpy-arrays"},{"level":2,"text":"Let’s vectorize our binary search","id":"let-s-vectorize-our-binary-search"},{"level":3,"text":"Making all searches take the same number of steps","id":"making-all-searches-take-the-same-number-of-steps"},{"level":3,"text":"Can NumPy beat NumPy?","id":"can-numpy-beat-numpy"},{"level":3,"text":"Can we optimize NumPy?","id":"can-we-optimize-numpy"},{"level":3,"text":"Porting it into C++","id":"porting-it-into-c"},{"level":3,"text":"Ecosystem Comparison","id":"ecosystem-comparison"},{"level":3,"text":"Conclusion","id":"conclusion"}]}}