This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is indexOf() in String class expensive operation?

 
Rudy Rusli
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Henry Wong
author
Marshal
Pie
Posts: 21117
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic