Comparison of Three String concatenation Modes

Source: Internet
Author: User

Comparison of Three String concatenation Modes

String operations in Java can be said to be the most common. There are three String concatenation methods in string operations. Let's take a look at the differences between the three methods, when to use it.

1. time consumption

Let's take a look at a piece of code:

Package com. codeing. snail Il. test; public class StringFormat {private static long startPointTime; public static void main (String [] args) {String s1 = "James"; String s2 = "and "; string s3 = "Xiaoqiang"; String s4 = "LOL"; startPointTime = System. currentTimeMillis (); strFormat2 (s1, s2); printTimeAndClear (); strFormat1 (); printTimeAndClear (); strFormat3 (s1, s2, s3, s4); printTimeAndClear ();} private static String strFormat3 (String s1, String s2, String s3, String s4) {StringBuilder sb = new StringBuilder (); sb. append (s1); sb. append (s2); sb. append (s3); sb. append (s4); return sb. toString ();} private static String strFormat2 (String s1, String s2) {return s1 + "and" + s2 + "together with LOL";} private static String strFormat1 () {return String. format ("% s and % s together LOL", new String [] {"Xiao Ming", "Xiao Qiang"});} private static void printTimeAndClear () {System. out. println (System. currentTimeMillis ()-startPointTime); startPointTime = System. currentTimeMillis ();}}
Output result:

From the above results, we can see that it is time-consuming to use the format method when splicing strings, but it is too early to come to the conclusion. Let's take a look at it for 1000 times in a loop.

Package com. codeing. snail Il. test; public class StringFormat {private static long startPointTime; public static void main (String [] args) {String s1 = "James"; String s2 = "and "; string s3 = "Xiaoqiang"; String s4 = "LOL"; startPointTime = System. currentTimeMillis (); strFormat2 (s1, s2); printTimeAndClear (); // strFormat1 (); // printTimeAndClear (); strFormat3 (s1, s2, s3, s4 ); printTimeAndClear ();} private static String strForma T3 (String s1, String s2, String s3, String s4) {StringBuilder sb = new StringBuilder (); for (int I = 0; I <1000; I ++) {sb. append (String. valueOf (I);} return sb. toString ();} private static String strFormat2 (String s1, String s2) {String str = "begin"; for (int I = 0; I <1000; I ++) {str = str + String. valueOf (I);} return str;} private static String strFormat1 () {String str = "begin"; String [] strArr = new St Ring [1000]; for (int I = 0; I <strArr. length; I ++) {strArr [I] = String. valueOf (I);} // Let me do it. This won't let me write 1000 matching characters... Obviously, this method is not suitable for a large number of stitching. // Return String. format ("% s ...... ", strArr); return str;} private static void printTimeAndClear () {System. out. println (System. currentTimeMillis ()-startPointTime); startPointTime = System. currentTimeMillis ();}}
Output result:

The above is the result of concatenating strings with "+". The following is the result of using StringBuilder. It is obvious that it is better to splice strings with "+" in the case of frequent concatenation, in this case, format is not considered.

Comprehensive comparison: StringBuilder wins. If many concatenated strings exist, time consumption can be prioritized.

2. From the perspective of memory consumption, we need to find the answer from the source code. Let's first look at the source code of StringBuilder:
    public AbstractStringBuilder append(String str) {        if (str == null)            return appendNull();        int len = str.length();        ensureCapacityInternal(count + len);        str.getChars(0, len, value, count);        count += len;        return this;    }
Value is of the char [] type. We can see that the principle of String concatenation is achieved by copying character arrays. In fact, the essence of adding two strings is the addition of StringBuilder, but redundant string objects will be created. Let's take a look at the source code of String. format:
    public static String format(String format, Object... args) {        return new Formatter().format(format, args).toString();    }
Java. util. the Formatter class may be familiar to everyone. This is the class for formatting text output, such as date and amount. Our most common System. out. println () is also implemented by calling the format method of this class. The Formatter construction method is as follows:
    public Formatter() {        this(Locale.getDefault(Locale.Category.FORMAT), new StringBuilder());    }
    /* Private constructors */    private Formatter(Locale l, Appendable a) {        this.a = a;        this.l = l;        this.zero = getZero(l);    }
We can see that a StringBuilder is created as the global variable of Formatter.
    public Formatter format(Locale l, String format, Object ... args) {        ensureOpen();        // index of last argument referenced        int last = -1;        // last ordinary index        int lasto = -1;        FormatString[] fsa = parse(format);        for (int i = 0; i < fsa.length; i++) {            FormatString fs = fsa[i];            int index = fs.index();            try {                switch (index) {                case -2:  // fixed string, "%n", or "%%"                    fs.print(null, l);                    break;                case -1:  // relative index                    if (last < 0 || (args != null && last > args.length - 1))                        throw new MissingFormatArgumentException(fs.toString());                    fs.print((args == null ? null : args[last]), l);                    break;                case 0:  // ordinary index                    lasto++;                    last = lasto;                    if (args != null && lasto > args.length - 1)                        throw new MissingFormatArgumentException(fs.toString());                    fs.print((args == null ? null : args[lasto]), l);                    break;                default:  // explicit index                    last = index - 1;                    if (args != null && last > args.length - 1)                        throw new MissingFormatArgumentException(fs.toString());                    fs.print((args == null ? null : args[last]), l);                    break;                }            } catch (IOException x) {                lastException = x;            }        }        return this;    }
In the format method, we can see that the print method of a FormatString is as follows:
        public void print(Object arg, Locale l)            throws IOException { a.append(s); }
A is the StringBuilder we created above. Now we understand that the original String. format is also implemented by StringBuilder. Through the above analysis, we can conclude that StringBuilder is the basic implementation of the other two methods, so StringBuilder is dominant. Vc + 24NTyv8nS1NPFz8i/samples/bV4tH5tcS94cLbo6zU2sq508O088G/19a3 + Serial + yc/serial = "+" # concatenated strings seem to have no advantages. Why do we need to compare them? In fact, for some occasions (such as splicing two strings) we can use these two methods for program readability, conciseness, and other factors. You can also use String. format to concatenate a String in a special format (such as a date display) or a progress scale.



Related Article

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.