Know the two of the String: String and StringBuffer

xiaoxiao2021-03-06  108

In Java, the String class is provided to simplify the operation of the string. This is more convenient than C, but some people have made String's performance, and you can mention an example:

String a = "hello";

String b = "litter";

String c = "pig";

String D = "!";

String result = a b C D;

It will be considered that this code produces seven String objects, A, B, C, D four, then A B C D generates 3, producing excess temporary objects, for repeatedly run Java programs to performance There is a big impact (because the garbage collector is sick).

In fact, this example should be an example of two years. Now the compiler has been optimized for these code, compiled into the following:

String a = "hello";

String b = "litter";

String c = "pig";

String D = "!";

String results = new stringbuffer (). Append (a) .append (b) .append (c) .append (d) .tostring ();

Therefore, six objects are generated, 5 string objects, a StringBuffer temporary object. Maybe you want to personally verify that it is true, it may be anti-compile code. However, most anti-compilers have done anti-compilation optimization, and what you see is still Result = A B C D :), You can confirm my saying by viewing the bytecode, or with the performance tuning tool to view the generated object.

String is a non-variable class, which changes to strign, such as String str = "Hell Pig"; string newstr = str.trim (); generated new object may have an impact on performance, but not all About String operations will result in poor performance, just as TRIM methods, the actual operation should be generated by the new String object using the original String object's Char array (the string is actually composed of the Char array), just changing the indicator string The same value. The same StringBuffer's toString method also has a new char [] array, and he is still with the obtained String a char array (unless the StringBuffer object has changed, this time, StringBuffer will no longer share with String. Array, but generate a new array), you can view StringBuffer, get validation with the source code of the String class.

转载请注明原文地址:https://www.9cbs.com/read-95832.html

New Post(0)