This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Is indexOf() in String class expensive operation? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Is indexOf() in String class expensive operation?" Watch "Is indexOf() in String class expensive operation?" New topic

Is indexOf() in String class expensive operation?

Rudy Rusli
Ranch Hand

Joined: Jun 01, 2006
Posts: 114
Is indexOf() in String class expensive operation? Because I imagine for example if a String has length 1000 and the last character is "a".
And I need to find an "a" in the String, it will go one by one until the 1000th character until it finds "a".

Is it better to user JAVA Regular Expression in all cases?

- Rudy -
Paul Clapham

Joined: Oct 14, 2005
Posts: 19728

You could run some tests and find out for yourself. But I can't imagine how a regular expression that simply searched for an "a" in a String could avoid looking at all the characters that the indexOf() method would look at. If anything I would expect the regex would be slower, because of the setup processing.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
In practice, indexOf() uses a fairly simple nested loop to search for the target string, while Pattern uses some more complicated, sophisticated techniques - including one called the Boyer-Moore algorithm. This means that for strings which are longer than length 1, Pattern may be able to give significantly faster searches than indexOf(). I think this would be true especially if both the target and input strings are large - the larger they are, the more benefit you get from Boyer-Moore and Pattern. However for short targets and especially for short input, Pattern has more overhead, and indexOf() will be faster. I encourage you to measure some sample times for various scenarios if this interests you.
[ October 03, 2007: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Henry Wong

Joined: Sep 28, 2004
Posts: 20057

Out of interest, I just tried it. I created a string, with a search string of size X at position 1000. The pattern for the regex was precompiled and not part of the processing time.

With X equal 1, the indexof operation was 10 times faster than the regex.

With X equal 1000, the indexof operation was only 2 times faster than the regex.

With X equal 100000, the indexof operation was up to 5 times faster than the reqex.

No conclusions. Just posting in case anyone is interested.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Have you checked out Aspose?
subject: Is indexOf() in String class expensive operation?
It's not a secret anymore!