String buffers
- Q: What is the difference between
String
andStringBuffer
? -
A: The main difference is that in Java
String
s are immutable, which makes them quite inefficient for concatenating large amounts of text, especially in extensive loops. For eachString
concatenation statement the Java runtime system must instantiate at least one additionalString
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 aString
? -
A: In most cases you should use a
StringBuffer
rather than string concatenation. The character content of JavaString
objects is immutable. Whenever you concatenate twoString
instances you actually create a thirdString
object for the result. This implicitString
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
orwhile
loop, or over many statement lines it is better to use aStringBuffer
, orStringBuilder
in single threaded applications. - Q: Why don't two
StringBuffer
s match? -
A: The
String
class overrides the default implementation of theequals(Object)
method to compare the string contents of each object. In this case equivalent string contents are considered equal. TheStringBuffer
class does not override the superclassObject
equals(Object)
method, which tests whether the argument refers to the same object reference. - Q: What's the difference in the memory allocation for
StringBuffer
s? -
A: The key difference between a
String
and aStringBuffer
in terms of memory allocation is thatString
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 ofStringBuffers
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. TheStringBuffer
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 chooseString
orStringBuffer
types appropriate to the task and set an adequate buffer size.
0 Comments:
Đăng nhận xét
<< Home