What is difference between String and String Builder/String Buffer?
>> Monday, May 30, 2011
String:
1.)String is immutable: you can’t modify a string
object but can replace it by creating a new
instance. Creating a new instance is rather
expensive.
2.)//Inefficient version using immutable String
String output = “Some text”
Int count = 100;
for(int i =0; i<count; i++) {
output += i;
}
return output;
3.)3.)The above code would build 99 new String
objects, of which 98 would be thrown away
immediately. Creating new objects is not
efficient.
StringBuffer / StringBuilder (added in J2SE 5.0)
1.)StringBuffer is mutable: use StringBuffer or StringBuilder when you want
to modify the contents. StringBuilder was added in Java 5 and it is
identical in all respects to StringBuffer except that it is not synchronized,
which makes it slightly faster at the cost of not being thread-safe.
2.)//More efficient version using mutable StringBuffer
StringBuffer output = new StringBuffer(110);// set an initial size of 110
output.append(“Some text”);
for(int i =0; i<count; i++) {
output.append(i);
}
return output.toString();
3.)The above code creates only two new objects, the StringBuffer and the
final String that is returned. StringBuffer expands as needed, which is
costly however, so it would be better to initialize the StringBuffer with the
correct size from the start as shown.
1.)String is immutable: you can’t modify a string
object but can replace it by creating a new
instance. Creating a new instance is rather
expensive.
2.)//Inefficient version using immutable String
String output = “Some text”
Int count = 100;
for(int i =0; i<count; i++) {
output += i;
}
return output;
3.)3.)The above code would build 99 new String
objects, of which 98 would be thrown away
immediately. Creating new objects is not
efficient.
StringBuffer / StringBuilder (added in J2SE 5.0)
1.)StringBuffer is mutable: use StringBuffer or StringBuilder when you want
to modify the contents. StringBuilder was added in Java 5 and it is
identical in all respects to StringBuffer except that it is not synchronized,
which makes it slightly faster at the cost of not being thread-safe.
2.)//More efficient version using mutable StringBuffer
StringBuffer output = new StringBuffer(110);// set an initial size of 110
output.append(“Some text”);
for(int i =0; i<count; i++) {
output.append(i);
}
return output.toString();
3.)The above code creates only two new objects, the StringBuffer and the
final String that is returned. StringBuffer expands as needed, which is
costly however, so it would be better to initialize the StringBuffer with the
correct size from the start as shown.
0 comments:
Post a Comment