♂To Live Is To Fight™ !♀
      $ = №1 * ♀ = №2

Thứ Bảy, 23 tháng 10, 2010

String buffers

Q: What is the difference between String and StringBuffer?

A: The main difference is that in Java Strings are immutable, which makes them quite inefficient for concatenating large amounts of text, especially in extensive loops. For each String concatenation statement the Java runtime system must instantiate at least one additional String object and then dispose of it. StringBuffer is designed exactly to overcome this problem, to build string content in an editable internal buffer without generating lots of additional objects. StringBuffer has many convenience methods to append all Java primitive types, character arrays and objects, and to check and manipulate characters in the buffer.

Q: When should I use a StringBuffer instead of a String?

A: In most cases you should use a StringBuffer rather than string concatenation. The character content of Java String objects is immutable. Whenever you concatenate two String instances you actually create a third String object for the result. This implicit String object creation can slow down your program, increase the number of objects in the runtime system and the garbage collection required to dispose of the temporary strings.

On a small scale, string concatenation is unlikely to have a significant performance impact, but if you are building strings in a for or while loop, or over many statement lines it is better to use a StringBuffer, or StringBuilder in single threaded applications.

Q: Why don't two StringBuffers match?

A: The String class overrides the default implementation of the equals(Object) method to compare the string contents of each object. In this case equivalent string contents are considered equal. The StringBuffer class does not override the superclass Object equals(Object) method, which tests whether the argument refers to the same object reference.

Q: What's the difference in the memory allocation for StringBuffers?

A: The key difference between a String and a StringBuffer in terms of memory allocation is that String objects are immutable; once the string contents are set they cannot be changed, so the virtual machine can optimise memory use on this basis. The content of StringBuffers can be expanded beyond their initial buffer size, so the memory allocation needs to be variable and must be managed by the Java runtime system. The StringBuffer class automatically adjusts its buffer size to fit the string content it is given, but you should instantiate the class with an explicit buffer size large enough to avoid the performance overhead associated with such resizes.

StringBuffer buffer = new StringBuffer(1024);       

Java programmers should not be concerned with detailed level memory management for String operations, which will be handled and optimised by the runtime system. The key things are to choose String or StringBuffer types appropriate to the task and set an adequate buffer size.