Come to a simple topic today and relax for a moment:)
Believe that a lot of people are not unfamiliar with this problem, as long as a Java programmer, must have used these several classes:
1. String is an immutable object, which means that each string concatenation creates a new instance
2, StringBuilder and StringBuffer are specifically used to do string splicing
3, StringBuffer is thread-safe, StringBuilder is thread insecure
4, thread safety is to pay the price, so stringbuffer than StringBuilder to a little slower
OK, does the top four article recite? Then ask a specific question:
1, the following fictitious three kinds of writing which speed is the fastest? Which is the worst?
String str = new StringBuilder ("I"). Append ("Love"). Append ("Java"). Append ("Python"). Append (...). Append ("Golang"). ToString (); String str = new StringBuilder ("I"). Append ("Love"). Append ("Java"). Append ("Python"). Append (...). Append ("Golang"). ToString (); String str = new StringBuffer ("I"). Append ("Love"). Append ("Java"). Append ("Python"). Append (...). Append ("Golang"). ToString ();
Answer: Because all are string literal, the first one is the fastest, in the JVM appears to be the equivalent of string str = "Ilovejavapython ... Golang ", of course, so write is pure egg pain, in order to examine the knowledge point just, gentlemen laugh:) The Third Kind uses the StringBuffer the slowest, hehe
What if it's written like this?
String a = "I"; String B = "Love"; String c = "Java"; String d = "Python"; ... String e = "Golang"; String str = a + B + C + D + ... + e;
The use of a + connection between variables is no longer a string literal, this will be the slowest drop
2, another look, Q: The following method can be used in multi-threaded environment?
public static string Build (String ... args) { StringBuilder buf = new StringBuilder (); for (int i = 0; i < args.length; i++) { buf.append (args[i]); } return buf.tostring (); }
Answer: The StringBuilder here is a local variable, although the StringBuilder itself is thread insecure, but used here without any problem ha:)
This is the eighth interview question, a person daily update is too difficult to adhere to, beg for contributions, please submit:)
This article from the public number: It_mianshiti
[One question per day] vs. String, StringBuffer, StringBuilder in Java