String algorithms
String algorithms are the methods programs use to find, match and index text. They cover searching for one pattern or many, regular expressions, text indexes and the distance between two strings. Benchmarks agree that no single method wins: the leader changes with pattern length, alphabet size, setup cost and the result asked for (Tarhio et al., 2017; Marino & Tarhio, 2026; Gallant & memchr contributors, n.d.; Ferragina et al., 2008). Open questions include how much specialised code gains over standard libraries once setup is counted, and what “linear-time” regex guarantees cover. Others are how often slow regular expressions are exploitable in deployed software, and whether old gaps between compressed and plain text indexes still hold.
How these choices fit among other data structures is the subject of Choosing algorithms and data structures.
Searching for one pattern
For a single exact pattern, the fastest algorithm depends on how long the pattern is and how many distinct symbols the text uses (its alphabet). Many fast methods rely on SIMD (single instruction, multiple data) instructions, which compare several bytes in one step.
Short patterns favour SIMD scanning. In an x86 benchmark that counted every match, the authors’ SIMD scan was fastest for patterns up to about 50 symbols (Tarhio et al., 2017). Two older algorithms, EPSM and SBNDM4, kept an advantage for long patterns on small alphabets (Tarhio et al., 2017).
Later comparisons keep finding different leaders in different regions. On random text, methods designed for long patterns, such as SSB, did better as patterns and alphabets grew (Marino & Tarhio, 2026). Variants of one algorithm can also differ widely. On English text, an EPSM variant using CRC32C hashing ran up to 5.3 times faster than the original, for a 4,096-symbol pattern (Marino & Tarhio, 2026). A tuned AVX2 version of EPSM gained most over the original below 16 symbols (Aydoğmuş & Külekci, 2019).
Setup cost and one-off searches Weak evidence: few or small studies support this
Evidence on one-off searches is thin: for a single search, the time spent building a searcher can cancel much of a faster algorithm’s gain. In its maintainer’s benchmark, the Rust memchr library’s lead over the Rust standard library shrank when construction time was counted (Gallant & memchr contributors, n.d.). The comparison is imperfect, because the standard library offers no way to build a searcher once and reuse it (Gallant & memchr contributors, n.d.).
Libraries respond by choosing a cheap method for tiny inputs. On very small texts, memchr uses Rabin–Karp, which compares a hash of each text window with the pattern’s hash. Its overhead is so small that it often finishes before other searchers are built (Gallant & memchr contributors, n.d.).
What standard libraries ship
The three runtimes below promise only the first match, and their implementations choose or switch algorithms depending on the input. The table describes the listed versions; the public documentation fixes only the return value.
| Runtime | What the call returns | How the listed version searches |
|---|---|---|
Python 3.14, str.find | Lowest position of the substring within the requested slice, or −1 (Python Software Foundation, n.d.a) | Forward search can switch to the Two-Way algorithm after partial comparisons accumulate in proportion to the pattern length (Python Software Foundation, n.d.o) |
Go 1.25, strings.Index | Index of the first occurrence, or −1 (The Go Authors, n.d.d) | A first-byte scan switches to another routine when it gives too many false candidates; long patterns can switch to Rabin–Karp after enough failed checks (The Go Authors, n.d.c) |
Java (OpenJDK 25), String.indexOf | Index of the first occurrence, or −1 (Oracle and/or its affiliates, n.d.a) | Routes the search to a Latin-1 or a UTF-16 routine by string encoding (Oracle and/or its affiliates, n.d.a); the Latin-1 routine is marked as a candidate for a hand-written machine-code replacement (an intrinsic) (Oracle and/or its affiliates, n.d.b) |
Searching for many patterns at once
The classic method for many patterns is Aho–Corasick, which builds one automaton (a state machine) from all patterns and reads the text once. Its measured speed depends on how the automaton is stored and how many patterns there are.
For small sets of literal strings, libraries can skip the automaton. The Rust aho-corasick crate can use a routine called Teddy that confirms its own matches, so the automaton may not run at all (Gallant, n.d.). When the text is shorter than Teddy’s minimum, the crate uses Rabin–Karp instead (Gallant, n.d.).
For large dictionaries, the memory layout of the automaton matters. In a Japanese tokenizer, a compact double-array automaton that steps one character at a time took 2.9 microseconds per sentence, against 7.3 and 7.5 for two standard Aho–Corasick implementations (Kanda et al., 2023). Its character-wise variants beat its byte-wise variant because they made fewer random memory accesses (Kanda et al., 2023).
Filters built on q-grams (short runs of adjacent symbols) can beat Aho–Corasick on large random pattern sets. For 10,000 random eight-symbol patterns over a 256-symbol alphabet, one such filter ran 16 times faster than the Aho–Corasick implementation it was compared with (Salmela et al., 2006). In a later preprint on English text, a q-gram method searched for 10,000 patterns of length 32. It slightly exceeded 100 MB per second, while the two slowest methods tested were ten times slower (Susik et al., 2014).
Regular expression engines
Regular-expression engines fall into two families. Backtracking engines try alternatives one at a time and can take exponential time on some patterns; automaton engines bound the work by the length of the text.
How automaton engines work
Automaton engines trade build cost against matching speed. A Thompson NFA (nondeterministic finite automaton) keeps a set of possible states and advances each of them on every input symbol (Rust regex-automata contributors, n.d.). A DFA (deterministic finite automaton) has only one state at a time, which makes matching fast, but it can take exponential time or space to build (Rust regex-automata contributors, n.d.).
Hybrid engines avoid that cost by building DFA states only as the text needs them. The Rust regex-automata hybrid keeps a DFA’s fast search without its exponential build time (Rust regex-automata contributors, n.d.). The .NET 7 non-backtracking engine starts with such a lazy DFA and switches to NFA processing if the DFA grows too large (Toub, 2022).
The trade-off shows in measurements. In a 2019 evaluation, the Symbolic Regex Matcher took longer to compile patterns than RE2 or .NET (Saarikivi et al., 2019). On one benchmark it had a lower mean matching time than RE2, which its authors attribute to RE2’s more severe slow outliers (Saarikivi et al., 2019).
What linear-time guarantees cover
Several engines guarantee time linear in the input, meaning time grows at most in proportion to text length for a fixed pattern. RE2 (RE2 contributors, n.d.) and Go’s standard regexp package (The Go Authors, 2026b) state this guarantee. .NET’s NonBacktracking mode is designed for time proportional to text length (Microsoft, 2023).
A guarantee for one search does not cover listing every match. The Rust regex crate bounds one search by O(m × n): time at most proportional to the pattern size m, which counts repetitions after expansion, times the text length n in bytes (Rust regex contributors, n.d.). Its match iterators, which return every match in turn, can rescan the text and have a worst case of O(m × n²) (Rust regex contributors, n.d.).
Some features beyond the basic syntax can keep the bound. A lookaround checks the text just before or after a match without consuming it. The RE# engine supports restricted lookarounds, and its authors prove its main matching algorithm is linear in the input (Varatalu et al., 2025).
Catastrophic backtracking and ReDoS
A backtracking engine can take far longer than linear time on certain inputs, called catastrophic backtracking. An attacker who supplies such input can tie up a server, an attack known as regular-expression denial of service (ReDoS). Microsoft recommends setting a timeout when a regular expression relies on backtracking or receives untrusted input (Microsoft, 2023). See also Web security.
Slow regular expressions are common in libraries, but how often they are exploitable in deployed systems rests on few measurements. A 2018 study found thousands of superlinear regular expressions affecting over 10,000 JavaScript and Python modules (Davis et al., 2018). Its authors did not check whether malicious input could reach them (Davis et al., 2018). A 2022 study that did test live websites found 6 vulnerable domains among 475 with published API specifications (Barlas et al., 2022). The first counts library modules and the second live web domains, so the two figures do not compare directly (Davis et al., 2018; Barlas et al., 2022).
Inside grep and ripgrep
Fast text-search tools use literal strings to filter before running the full regular expression. GNU grep 3.11 combines a lazily built DFA with Boyer–Moore and Aho–Corasick searches for fixed strings (Free Software Foundation, 2023). Ripgrep finds candidate lines with a literal filter and runs the full regex engine only on those lines (Gallant, 2016).
The workload decides how much any tool’s speed matters. In the ripgrep project’s own benchmarks, many matches often narrowed the differences between tools (Gallant & ripgrep contributors, n.d.). Searching large files for a pattern with no literal to filter on made performance drop sharply across all tools (Gallant & ripgrep contributors, n.d.).
Indexes for repeated searches
For a body of text searched many times, the kind of query decides which index fits. A positional inverted index records where each word occurs and answers phrase queries by intersecting those lists (Ferragina et al., 2008). For arbitrary substrings, a suffix array (every position in the text, sorted by the text that follows it) answers queries that cross word boundaries. Compressed self-indexes such as the FM-index can reproduce any part of the text, so they replace the original text (Ferragina et al., 2008).
Compressed indexes save space at the cost of speed, and the cost is largest when every match must be located. In the 2008 Pizza&Chili benchmark on English text, a plain suffix array counted matches in 0.512 microseconds per pattern symbol, at five times the size of the text. An FM-index variant took 2.694 microseconds at 0.42 times the text size, without the extra data needed to locate matches (Ferragina et al., 2008). To locate occurrences of five-symbol patterns, the plain suffix array was 100 to 1,000 times faster per occurrence than any compressed index tested (Ferragina et al., 2008).
Other designs win when patterns occur often. At comparable memory, inverted files that index fixed-length q-grams located patterns faster than compressed suffix arrays when there were many occurrences (Puglisi et al., 2006).
Recent large systems still report a penalty for locating. In Infini-gram mini, an FM-index over web-scale text, mapping every match back to its position in the original text was too slow for some uses (Xu et al., 2025f). Its document retrieval also remained slower than a plain suffix array (Xu et al., 2025f).
Edit distance and fuzzy matching
Edit distance, or Levenshtein distance, counts the fewest single-character insertions, deletions and substitutions that turn one string into another (Ding et al., 2023). Three tasks use it: comparing two strings, finding dictionary entries within an edit limit, and recovering the sequence of edits. The fastest method differs by task, by the edit limit and by the edit costs.
For short strings with a low edit limit, bit-parallel algorithms can lead. Bit-parallel methods pack many cells of the distance table into the bits of one machine word. One blog benchmark matched a name against 1,000 candidates with a three-edit cutoff. A prepared Myers bit-parallel implementation averaged 5.415 microseconds, against 51.068 for the same author’s bounded Ukkonen implementation (Hallman, 2026).
Libraries pick an algorithm by cutoff and edit costs. RapidFuzz uses the mbleven algorithm when the cutoff is three or less with equal edit costs (Bachmann, n.d.). For other edit costs it uses Wagner–Fischer, the classic table-filling dynamic program (Bachmann, n.d.).
Searching a large dictionary costs time in proportion to the candidates the search must consider. In dictionary experiments at a fixed edit limit, correction time depended on the expected number of candidates, which fell for longer query words (Mihov & Schulz, 2004).
For long strings that differ by few edits, one parallel method stands out. In a benchmark of parallel algorithms on real-world data, a block-hashing approach generally led when the edit distance was small (Ding et al., 2023). That benchmark computed only the distance, not the sequence of edits (Ding et al., 2023).
Further reading
- Tarhio et al. (2017): a benchmark of exact single-pattern search showing SIMD scanning beating classic algorithms on short patterns, and where it stops winning.
- Kanda et al. (2023): how the memory layout of an Aho–Corasick automaton changes its speed on large dictionaries.
- Davis et al. (2018): the ecosystem-scale study of slow regular expressions in JavaScript and Python packages.
- Rust regex contributors (n.d.): documentation that states precisely what a linear-time regex guarantee covers, for one search and for iteration.
- Ferragina et al. (2008): the Pizza&Chili comparison of plain and compressed text indexes, for counting and locating matches.
- Gallant (2016): the ripgrep author’s account of how literal filtering and engine choice make a search tool fast.
First published .
Known gaps
What this article cannot tell you yet.
- String hashing and fingerprinting (rolling hashes such as Rabin–Karp used for deduplication, and their collision risk) were not researched.
- No measurement isolates the input size or first-match position below which a simple scalar search beats a SIMD search.
- Whether the 2008 gap between plain suffix arrays and compressed indexes for locating many matches still holds was not measured with current implementations under matched conditions.
- How exposure to regular-expression denial of service has changed over time is not established: the two studies measured different populations.
- Current benchmarks of grep implementations on equal file sets, encodings and output were not researched.
- The cost of producing the sequence of edits, rather than only the distance, for long strings was not researched.
- Word-oriented compressed indexes compared with positional inverted indexes for document retrieval under memory limits were not researched.
References
- Solid source
- Rated highly trustworthy by the research, and every passage taken from it was found in it.
- Weak source
- Rated low, or a passage taken from it was not found in it.
- Medium trust
- Rated medium by the research.
- Not checked
- Rated high, but its passages could not all be checked against it.
Show all 34 references
- Gallant, A. (n.d.). DESIGN.md (aho-corasick 1.1.5). Docs.rs. https://docs.rs/crate/aho-corasick/latest/source/DESIGN.md Solid source Documentation, read in large part.
- Aydoğmuş, M. A., & Külekci, M. O. (2019). Optimizing packed string matching on AVX2 platform. High Performance Computing for Computational Science, VECPAR 2018. https://www.academia.edu/41955916/Optimizing_Packed_String_Matching_on_AVX2_Platform Medium trust Peer-reviewed, read in large part.
- Barlas, E., Du, X., & Davis, J. C. (2022). Exploiting input sanitization for regex denial of service. 44th International Conference on Software Engineering. https://davisjam.github.io/files/publications/BarlasDuDavis-WebREDOS-ICSE2022.pdf Solid source Peer-reviewed, read in large part.
- Python Software Foundation (n.d.o). fastsearch.h. CPython v3.14.0. https://raw.githubusercontent.com/python/cpython/v3.14.0/Objects/stringlib/fastsearch.h Solid source Documentation, read in full.
- Davis, J. C., Coghlan, C. A., Servant, F., & Lee, D. (2018). The impact of regular expression denial of service (ReDoS) in practice: An empirical study at the ecosystem scale. Proceedings of the 26th ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering (ESEC/FSE 18). https://davisjam.github.io/files/publications/DavisCoghlanServantLee-EcosystemREDOS-ESECFSE18.pdf Solid source Peer-reviewed, read in large part.
- Ding, X., Dong, X., Gu, Y., Liu, Y., & Sun, Y. (2023). Efficient parallel output-sensitive edit distance. 31st Annual European Symposium on Algorithms (ESA 2023). https://drops.dagstuhl.de/storage/00lipics/lipics-vol274-esa2023/LIPIcs.ESA.2023.40/LIPIcs.ESA.2023.40.pdf Solid source Peer-reviewed, read in large part.
- Ferragina, P., González, R., Navarro, G., & Venturini, R. (2008). Compressed text indexes: From theory to practice. ACM Journal of Experimental Algorithmics. https://pages.di.unipi.it/rossano/assets/pdf/papers/JEA08.pdf Solid source Peer-reviewed, read in large part.
- Free Software Foundation (2023). GNU grep 3.11 README. GNU grep 3.11 source distribution. https://sources.debian.org/src/grep/3.11-4/README Solid source Documentation, read in large part.
- Gallant, A. (2016). ripgrep is faster than grep, ag, git grep, ucg, pt, sift. Andrew Gallant's Blog. https://burntsushi.net/ripgrep/ Medium trust Blog post, read in large part.
- The Go Authors (2026b). regexp package - regexp. Go Packages. https://pkg.go.dev/regexp Solid source Documentation, read in large part.
- The Go Authors (n.d.d). strings.go, public strings package. Go 1.25.0. https://raw.githubusercontent.com/golang/go/go1.25.0/src/strings/strings.go Solid source Documentation, read in full.
- The Go Authors (n.d.c). strings.go, internal substring search. Go 1.25.0. https://raw.githubusercontent.com/golang/go/go1.25.0/src/internal/stringslite/strings.go Solid source Read in full.
- Hallman, C. (2026). Optimizing Levenshstein for fuzzy name matching. Connor Hallman (blog). https://connorhallman.com/blog/optimizing-levenshtein Solid source Blog post, read in large part.
- Kanda, S., Akabe, K., & Oda, Y. (2023). Engineering faster double-array Aho–Corasick automata. Software: Practice and Experience. https://arxiv.org/html/2207.13870 Solid source Peer-reviewed, read in large part.
- Marino, F. P., & Tarhio, J. (2026). Improving string matching through enhanced hashing. Software: Practice and Experience. https://onlinelibrary.wiley.com/doi/10.1002/spe.70087?af=R Solid source Peer-reviewed, read in large part.
- Gallant, A., & memchr contributors (n.d.). memchr. GitHub. https://github.com/BurntSushi/memchr Medium trust Documentation, read in large part.
- Microsoft (2023). Backtracking in regular expressions. Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/standard/base-types/backtracking-in-regular-expressions Solid source Documentation, read in large part.
- Mihov, S., & Schulz, K. U. (2004). Fast approximate search in large dictionaries. Computational Linguistics. https://www.cis.uni-muenchen.de/download/publikationen/fastapproxsearch.pdf Solid source Peer-reviewed, read in large part.
- Oracle and/or its affiliates (n.d.b). StringLatin1.java. OpenJDK 25 build 36. https://raw.githubusercontent.com/openjdk/jdk/jdk-25%2B36/src/java.base/share/classes/java/lang/StringLatin1.java Solid source Read in full.
- Oracle and/or its affiliates (n.d.a). String.java. OpenJDK 25 build 36. https://raw.githubusercontent.com/openjdk/jdk/jdk-25%2B36/src/java.base/share/classes/java/lang/String.java Solid source Documentation, read in full.
- Puglisi, S. J., Smyth, W. F., & Turpin, A. (2006). Inverted files versus suffix arrays for locating patterns in primary memory. String Processing and Information Retrieval. https://researchportal.murdoch.edu.au/esploro/outputs/journalArticle/Inverted-files-versus-suffix-arrays-for/991005541091207891 Medium trust Peer-reviewed, abstract only.
- Python Software Foundation (n.d.a). Built-in types. Python 3.14 documentation. https://docs.python.org/3.14/builtins/stdtypes.html#str.find Solid source Documentation, read in large part.
- Bachmann, M. (n.d.). Levenshtein. RapidFuzz documentation. https://rapidfuzz.github.io/RapidFuzz/Usage/distance/Levenshtein.html Solid source Documentation, read in large part.
- RE2 contributors (n.d.). RE2. GitHub. https://github.com/google/re2 Solid source Documentation, read in large part.
- Rust regex-automata contributors (n.d.). NFA in regex_automata::nfa::thompson - Rust. Docs.rs. https://docs.rs/regex-automata/latest/regex_automata/nfa/thompson/struct.NFA.html Weak source Documentation, read in large part.
- Gallant, A., & ripgrep contributors (n.d.). ripgrep. GitHub. https://github.com/BurntSushi/ripgrep Medium trust Documentation, read in large part.
- Rust regex contributors (n.d.). regex - Rust. Docs.rs. https://docs.rs/regex/latest/regex/ Solid source Documentation, read in large part.
- Saarikivi, O., Veanes, M., Wan, T., & Xu, E. (2019). Symbolic regex matcher. Tools and Algorithms for the Construction and Analysis of Systems. https://www.microsoft.com/en-us/research/wp-content/uploads/2019/02/SRM_tacas19.pdf Solid source Peer-reviewed, read in large part.
- Salmela, L., Tarhio, J., & Kytöjoki, J. (2006). Multi-pattern string matching with q-grams. ACM Journal of Experimental Algorithmics. https://users.aalto.fi/~tarhio/papers/jea.pdf Medium trust Peer-reviewed, read in large part.
- Susik, R., Grabowski, S., & Fredriksson, K. (2014). Multiple pattern matching revisited. arXiv. https://arxiv.org/pdf/1405.5483 Solid source Peer-reviewed, read in large part.
- Tarhio, J., Holub, J., & Giaquinta, E. (2017). Technology beats algorithms (in exact string matching). Software: Practice and Experience. https://onlinelibrary.wiley.com/doi/full/10.1002/spe.2511 Solid source Peer-reviewed, read in large part.
- Toub, S. (2022). Regular expression improvements in .NET 7. .NET Blog. https://devblogs.microsoft.com/dotnet/regular-expression-improvements-in-dotnet-7/ Medium trust Vendor page, read in large part.
- Varatalu, I. E., Veanes, M., & Ernits, J. (2025). RE#: High performance derivative-based regex matching with intersection, complement, and restricted lookarounds. Proceedings of the ACM on Programming Languages. https://www.microsoft.com/en-us/research/wp-content/uploads/2025/01/popl25-p2-final.pdf Medium trust Peer-reviewed, read in large part.
- Xu, H., Liu, J., Choi, Y., Smith, N. A., & Hajishirzi, H. (2025f). Infini-gram mini: Exact n-gram search at the internet scale with FM-index. Proceedings of the 2025 Conference on Empirical Methods in Natural Language Processing. https://aclanthology.org/2025.emnlp-main.1268.pdf Solid source Peer-reviewed, read in large part.