Little Experience in String, StringBuffer, and StringBuilder ......, Bufferbuilder
I think everyone is familiar with String, StringBuffer, and StringBuilder. These three often appear in our interview questions. I also saw the classic interview questions about these three questions, I have touched some of my previous work experiences. based on my own experience, I will write my own feelings and share them with you.
First, let's take a look at the two interview questions I have seen:
1.StringWhat is the difference between StringBuffer and StringBuffer? The efficiency is high.
A:String is an immutable class that operates on a String of characters.
StringBuffer operates on a string of characters, but it can be a variable class.
It is inefficient to generate a String every time it is used.
2.STringBuffer andSWhat are the differences between tringBuilder?
A:Stringbuilder and Stirngbuffer are variable objects. Stringbuilder runs fast and threads are insecure.
The answer to these two questions is correct, but how can we reasonably use these three questions in actual coding?
First, the String type is immutable, so we must remember that we cannot use a String to use a connection String in a loop, especially in web projects. When there are a large number of accesses, this method consumes a lot of resources. As follows:
1 // This connection method must avoid 2 for (int I = 0; I <100; I ++) {3 String a = ""; 4 String B = "B"; 5 System. out. println (a + B); 6}
So, under what conditions should String be used? Based on its immutable nature, we define the string as a static constant when we encounter a fixed string that is repeatedly used, and then useSTringBufferOrSTringBuilder. As follows:
1 public class StringTest {2 3 private static final String STRING = "day"; 4 5 public void setSystem () {6 StringBuilder f = new StringBuilder ("5"); 7 System. out. println (f. append (STRING); 8} 9 10 public static void main (String [] args) {11 StringTest s = new StringTest (); 12 s. setSystem (); 13} 14}
Next, let's talk aboutSTringBufferAndSTringBuilder.
We know:SThe tringBuffer is thread-safe and slow.STringBuilder is insecure and fast.
We need to analyze whether to ensure thread security or speed.
We usually use the framework during web project development. We need to check whether the framework is single-threaded or multi-threaded. If the framework is thread-safe, then we can pursue speed and useSTringBuilderYou can. If it is insecure, it is best to useSTringBuffer.
However, this is not an absolute concept. You can flexibly choose based on project requirements during development.