String is immutable. Which is a flashy word for "doesn't change". So, behind the scenes java makes a new String every time you change a String - which is slow.
If you're working with Strings that change a lot, using a StringBuffer will be a lot more efficient. Here's an example:
Code:
import java.util.Date;
public class tmp {
public static void main(String argv[]) {
int MAX = 10000; // careful with large values here!
StringBuffer sb = new StringBuffer();
String s = new String();
long start = new Date().getTime();
for (int i=0;i<MAX;i++) {
sb.append("xXxXx");
}
long end = new Date().getTime();
System.out.println("StringBuffer takes " + (end-start) + " mS");
start = new Date().getTime();
for (int i=0;i<MAX;i++) {
s+="xXxXx";
}
end = new Date().getTime();
System.out.println("String takes " + (end-start) + " mS");
}
}
On one of my machines this gives:
Code:
maui:/home/charlie$ java tmp
StringBuffer takes 4 mS
String takes 7467 mS
maui:/home/charlie$
--
Charlie Harvey's website - linux, perl, java, anarchism and punk rock:
http://charlieharvey.org.uk