String connection in Sting:

String connection in Sting:

  • List common splicing methods for strings, and write use cases to derive performance differences between them?
1.package com.mage.changyonglei;  
1.public class Test {  
2.    public static void main(String[] args) {  
3.        test01();  
4.        test03();  
5.        test02();  
6.       
7.    }  
8.    public static void test01() {  
9.        long start = System.currentTimeMillis();  
10.        StringBuffer sb = new StringBuffer("a");  
11.        for(int i = 0;i<100000;i++) {  
12.            sb.append("c");  
13.        }  
14.        long end = System.currentTimeMillis();  
15.        System.out.println("append:"+(end-start));  
16.    }  
17.      
18.    public static void test02() {  
19.        long start = System.currentTimeMillis();  
20.        String sb = new String("a");  
21.        for(int i = 0;i<100000;i++) {  
22.            sb = sb+"c";  
23.        }  
24.        long end = System.currentTimeMillis();  
25.        System.out.println("+Number:"+(end-start));  
26.    }  
27.      
28.    public static void test03() {  
29.        long start = System.currentTimeMillis();  
30.        String sb = new String("a");  
31.        for(int i = 0;i<100000;i++) {  
32.             sb = sb.concat("c");  
33.        }  
34.        long end = System.currentTimeMillis();  
35.        System.out.println("concat:"+(end-start));  
36.    }  
37.      
38.}  

Operation result diagram:

Conclusion:

1. There are three common methods of string stitching: "+" number stitching, concat, append.

2... append splicing is generally used in StringBuilder or StringBuffer, and the splicing speed is the fastest.

3... Plus stitching is the fastest if the left and right sides are literal.

4. Splicing efficiency for this problem: append > concat >+

Posted by esport on Mon, 14 Oct 2019 12:57:38 -0700