We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Finding indexOf quicker
Page Index Toggle Pages: 1
Finding indexOf quicker (Read 815 times)
Finding indexOf quicker
Feb 17th, 2007, 10:18pm
 
Here's a small section of code that loads strings into an array, from a web page, and then concatenates all the strings into one long string, to search through for some specific text  (indexOf)...

The code works, but is extremely slow... and more experiences coders have any suggestions for optimizing what I'm trying to do here, or suggesting another way to go about it?

Code:

int pos = 0;
String friends_section = "";
String[] lines = loadStrings(profilePage);
for(int s=0; s<lines.length; s++) {
friends_section += lines[s];
}
Random generator = new Random();
int rand_friend_num = generator.nextInt(10);
println("Checking friend: " + rand_friend_num);
pos = friends_section.indexOf("ctl00_Main_ctl00_UserFriends1_FriendRepeater_ctl0" + rand_friend_num + "_friendLink");



Many thanks...
Re: Finding indexOf quicker
Reply #1 - Feb 18th, 2007, 2:18pm
 
When dealing with large Strings, concatenation is very slow (and consumes a lot of memory.)  Strings are immutable (meaning they cannot be changed) so every += requires a new String object to be made!

A StringBuffer is better.

Code:

StringBuffer sb = new StringBuffer();
for(int s=0; s<lines.length; s++) {
sb.append(lines[s]);
}
friends_section = sb.toString();


You could also just use Processing's "join()" function which  does the above for you.

http://processing.org/reference/join_.html
Re: Finding indexOf quicker
Reply #2 - Feb 19th, 2007, 12:37am
 
Awesome.. great to know.  Many thanks!

Much appreciated... I'll post back and let you know how much faster the my code ran Smiley
Re: Finding indexOf quicker
Reply #3 - Feb 19th, 2007, 12:54am
 
Wow, I would say... about 15 times as fast, conservative estimate!  Thanks again!
Page Index Toggle Pages: 1