String buffers
- Q: What is the difference between
StringandStringBuffer? -
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 eachStringconcatenation statement the Java runtime system must instantiate at least one additionalStringobject and then dispose of it.StringBufferis designed exactly to overcome this problem, to build string content in an editable internal buffer without generating lots of additional objects.StringBufferhas 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
StringBufferinstead of aString? -
A: In most cases you should use a
StringBufferrather than string concatenation. The character content of JavaStringobjects is immutable. Whenever you concatenate twoStringinstances you actually create a thirdStringobject for the result. This implicitStringobject 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
fororwhileloop, or over many statement lines it is better to use aStringBuffer, orStringBuilderin single threaded applications. - Q: Why don't two
StringBuffers match? -
A: The
Stringclass 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. TheStringBufferclass does not override the superclassObjectequals(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
Stringand aStringBufferin terms of memory allocation is thatStringobjects 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 ofStringBufferscan be expanded beyond their initial buffer size, so the memory allocation needs to be variable and must be managed by the Java runtime system. TheStringBufferclass 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
Stringoperations, which will be handled and optimised by the runtime system. The key things are to chooseStringorStringBuffertypes appropriate to the task and set an adequate buffer size.



0 Comments:
Đăng nhận xét
<< Home