Code optimization

String : String is a final class. After initialization, it will not be changed. Try not to use + to concatenate strings. Here are a few chestnuts:

 

Fragment 1: Forbid the use of + to concatenate strings in the loop body

 

        /**
         * Forbid the use of + to concatenate strings in the loop body
         * */
        String result = "";
        for (int i = 0; i < 100; i++) {
            result += "z"; // result = new StringBuilder(result).append("z").toString(); each line produces a temporary StringBuilder
        }
        System.out.println(result);

 

Fragment 2: It is recommended to use StringBuilder for splicing strings

        StringBuilder result = new StringBuilder(); //This method is efficient
        for(int i=0;i<100;i++){
            result.append("z");
        }

 

Fragment 3: Do not splice more than two string objects in the append method of StringBuilder

        StringBuilder sb = new StringBuilder();
        String a = "a";
        String b = "b";
        sb.append(a + "," + b ); //Don't do this, (a + "," + b) will generate a temporary StringBuilder object during the splicing process

 

 Fragment 4: The addition of multiple strings will be appended through the intermediate temporary object StringBuilder object

        String result = "a" + "b" + "c" ; //The compiler will translate this step into: result = new StringBuilder("a").append("b").append("c").toString ();

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326488013&siteId=291194637