# Java's String.indexOf can be slow (quadratic)

DevFeed: [Java's String.indexOf can be slow (quadratic)](<https://devfeed.tech/articles/java-s-string-indexof-can-be-slow-quadratic-29424.md>)

Original publisher: [Read original article](<https://lemire.me/blog/2026/08/22/javas-string-indexof-can-be-slow-quadratic/>)

Author: Daniel Lemire

Published: 2026-08-22T14:56:16Z

Content type: article

Language: en

Sources: [Daniel Lemire](<https://devfeed.tech/sources/daniel-lemire.md>)

Topics: [Java](<https://devfeed.tech/topics/java.md>), [openjdk](<https://devfeed.tech/topics/openjdk.md>), [Programming](<https://devfeed.tech/topics/programming.md>)

Tags: [algorithm](<https://devfeed.tech/tags/algorithm.md>), [complexity](<https://devfeed.tech/tags/complexity.md>), [cpu](<https://devfeed.tech/tags/cpu.md>), [java](<https://devfeed.tech/tags/java.md>), [openjdk](<https://devfeed.tech/tags/openjdk.md>), [programming-language](<https://devfeed.tech/tags/programming-language.md>)

## AI overview

Java's String.indexOf can exhibit O(n-m) behavior on adversarial inputs with long substrings. The article compares it with the Two-Way algorithm and explains why Java's implementation remains suitable for typical workloads.

## Source excerpt

In Java, you find the location of a substring using indexOf. String haystack = "The quick brown fox jumps over the lazy dog"; String needle = "fox"; int index = haystack.indexOf(needle); Naively, you might implement indexOf by a loop inside a loop, like so. int naiveIndexOf(String haystack, String needle) { for (int i = 0; ... Continue reading Java's String.indexOf can be slow (quadratic)