String | StringBuffer / StringBuilder |
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.
//Inefficient version using immutable String
String output = “Some text” Int count = 100; for(int I =0; i output += i; } return output;
The above code would build 99 new String objects, of which 98 would be thrown away immediately. Creating new objects is not efficient.
| 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 synchronised, which makes it slightly faster at the cost of not being thread-safe.
//More efficient version using mutable StringBuffer
StringBuffer output = new StringBuffer(110); Output.append(“Some text”); for(int I =0; i output.append(i); } return output.toString();
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 initilise the StringBuffer with the correct size from the start as shown.
|
17. What is the main difference between a String and a StringBuffer class?
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment