String and StringBuilder of Java strings

Source: Internet
Author: User
Tags stringbuffer

some comparisons of string with Sringbuiler

?? In Java, we're going to use a lot of strings, but we probably didn't think much of how string works, in fact, in the string class, every method that looks like a string value is created with a completely new string object.
?? We can think about what happened when we used the + connection string and read a piece of code first.

public class Test2{    public String method1(String[] fields)    {        String result = "";        for(int i = 0; i < fields.length; i++)        {            result += fields[i];        }        return result;    }    public String method2(String[] fields)    {        StringBuilder result = new StringBuilder();        for(int i = 0; i < fields.length; i++)        {            result.append(fields[i]);        }        return result.toString();    }    public String method3()    {        String result = "aa" + "bb" + "cc";        return result;    }    public static void main(String[] args)    {        Test2 test = new Test2();        String[] str = {"a", "b", "c", "d", "e", "f", "g"};        System.out.println(test.method1(str));        System.out.println(test.method2(str));        System.out.println(test.method3());    }}

?? The method1 in the above code uses + to concatenate strings, while METHOD2 uses the StringBuilder append method to concatenate strings. Use the JAVAP command to disassemble the code.

Public java.lang.String method1 (java.lang.string[]);
Code:
0:LDC #2//String
2:astore_2
3:iconst_0
4:istore_3
5:iload_3
6:aload_1
7:arraylength
8:IF_ICMPGE 38
11:new #3//Class Java/lang/stringbuilder
14:dup
15:invokespecial #4//Method java/lang/stringbuilder. "

Public java.lang.String method2 (java.lang.string[]);
Code:
0:new #3//Class Java/lang/stringbuilder
3:dup
4:invokespecial #4//Method java/lang/stringbuilder. "

Public java.lang.String method3 ();
Code:
0:LDC #7//String AABBCC
2:astore_1
3:aload_1
4:areturn

?? As you can see, the 8 to 35 lines in METHOD1 are a loop body, and when we use + to concatenate strings, the compiler calls the StringBuilder append method, because it is more efficient, but in this loop body, Each cycle creates a StringBuilder object, resulting in a waste of resources.
?? In Method2, you can see that 13 to 27 rows are a loop body, and only one StringBuilder object is created in method2, saving resources.
?? In Method3, only three strings are added, and finally, the compiler optimizes this and generates a AABBCC string directly.
?? When using strings, it is important to note that when working with strings, you should consider using StringBuilder and Stringbuffer,stringbuffer as thread-safe, so the overhead will be greater.

    • Small amount of data using string
    • Single-threaded operation for large amounts of data using StringBuilder
    • Multi-threaded operation of large amounts of data using StringBuffer

?? Then a string comparison problem, also related to the above process, first look at a piece of code.

public class Test3{    public static void main(String[] args)    {        String str1 = "HelloWorld";        String str2 = "World";        String str3 = "Hello" + str2;        String str4 = "Hello" + "World";        System.out.println(str1 == str3);        System.out.println(str1 == str4);    }}

?? The output of this code is:

False
True

?? The result is that STR3 is actually the compiler to new a StringBuilder object , then append, and finally called the ToString () method, and STR4 through the compiler optimization, Generates a HelloWorld string directly, so the result is naturally true.

0:LDC #2//String HelloWorld
2:astore_1
3:LDC #3//String World
5:astore_2
6:new #4//Class Java/lang/stringbuilder
9:dup
10:invokespecial #5//Method java/lang/stringbuilder. "

?? The above is part of the disassembly of the code, you can see each string generation process, it is not difficult to understand the above comparison problem.

String and StringBuilder of Java strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.