We all know:
(1) Use String if you want to operate on a small amount of data;
(2) multithreaded operation StringBuffer under the operation of a large number of data StringBuffer;
(3) Single-threaded operation string buffer under the operation of a large number of data StringBuilder.
String is an immutable type, so it is less efficient than StringBuffer or StringBuilder. Why not use StringBuffer or StringBuilder directly when operating on a small amount of data?
(1) When working with small amounts of data, the immutable String has the advantage of not being changed
For example, StringBuffer StringBuffer = null; for example, StringBuffer StringBuffer = null; In this form, simply null to the object will not, but new StringBuffer(NULL) will emit a null pointer. Public StringBuffer(String var1) {super(var1.length() + 16); this.append(var1); }
(3) In some special cases, the String concatenation is actually interpreted by the JVM as a StringBuffer concatenation, so the String is not slower than the StringBuffer, especially in the following String generation, String S1 = “This is only a” + “simple” +” test”; StringBuffer Sb = new StringBuffer(“This is only a”).append(” simple”).append(” test”); You’ll be surprised how fast the String S1 object is generated, and the StringBuffer doesn’t have a speed advantage at all. String S1 = “This is only a” + “simple” + “test”; String S1 = “This is only a” + “simple” + “test”; String S1 = “This is only a simple test”;
So of course it doesn’t take much time. Note, however, that if your String is from another String, it’s not as fast. For example, String S2 = “This is only a”; String S3 = “simple”; String S4 = “test”; String S1 = S2 +S3 + S4; At this point, the JVM will do exactly what it did before