An
understanding of the difference between Java Strings
and StringBuffers can lead to great performance increases. Although it may seem
not to be the case given Java's String concatenation syntax (like
a=a+"hi"), Strings are in actuality read-only (ie, immutable) after
they are created so that they cannot change. As a result of this, when you
concatenate Strings via the + operator, in the background a temporary
StringBuffer gets created and the toString method is called on the StringBuffer
to create the new String, and this operation is fairly time-consuming.
However, much less overhead is required to concatenate a String
onto a StringBuffer object via the StringBuffer append method. You can
basically think of each append as adding another String piece into a linked
list that makes up the StringBuffer. So you basically have a StringBuffer
consisting of a String chunk which then points to another String chunk which
points to another String chunk, etc...
The benefits of StringBuffer become clear when you have a
situation involving many concatenations. To illustrate this, let's try
concatenating 10,000 "a" Strings together via the String + operator
and via a StringBuffer append method and monitor the time required to perform
these operations. The StringVersusStringBuffer class below illustrates this.
package test;
public class StringVersusStringBuffer {
public
static void main(String[] args) {
try {
final int NUM_REPEATS = 10000;
String string = "";
long start = System.currentTimeMillis();
for (int i = 0; i <
NUM_REPEATS; i++) {
string =
string + "a";
}
long end = System.currentTimeMillis();
System.out.println("String loop time
(ms): " + (end - start));
StringBuffer sb = new StringBuffer();
start =
System.currentTimeMillis();
for (int i = 0; i <
NUM_REPEATS; i++) {
sb.append("a");
}
end = System.currentTimeMillis();
System.out.println("StringBuffer
loop time (ms): " + (end - start));
} catch (Exception e) {
e.printStackTrace();
}
}
}
OutPut :
String loop time (ms) : 156
StringBuffer loop time (ms) : 0
No comments:
Post a Comment