| Author |
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
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
|
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
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
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
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
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. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
 |
|
|
subject: Is indexOf() in String class expensive operation?
|
|
|