In the for loop, string concatenation. Please replace the "+" splicing of String with the append splicing of StringBuilder.

In the splicing of for loop strings, many people write like this:

    public static void main(String[] args) {
        String str = "";
        for (int i = 0; i <= 15000; i++) {
            str="这是:" +i+ "!,";
        }
        System.out.println(str);
    }

If you are not in a for loop, it is understandable to use the "+" of string to splice; but in a for loop, this splicing is not recommended, because the String is converted to Stringbuilder, and then its append method is called.

In the for loop, each "+" operation actually creates a new StringBuilder, which results in multiple object creations and recycling, which consumes performance.

So it is recommended to write like this:

    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i <= 15000; i++) {
            stringBuilder.append("这是:").append(i).append("!,");
            stringBuilder.delete(0,stringBuilder.length());
        }
        System.out.println(stringBuilder);
    }

Putting new StringBuilder() outside the for loop effectively avoids performance consumption.

⚠️Note:

1. The string of append cannot be empty, and the value of append needs to be null-checked.

        Sanmu: Judgment conditions for fields? The result of true: the result of false.

two,

1. stringBuilder.delete(0,stringBuilder.length()) in the code;

        This is to clear the contents of stringBuilder in this cycle.

2. Clear the stringBuilder content. There are three ways:

        1. new, recycled by the recycling mechanism.

        2、stringBuilder的delete(0,stringBuilder.length())

        3、stringBuilder的setLength(0)

        Conclusion: The operating efficiency of these three methods is from high to low: 2>3>1

Guess you like

Origin blog.csdn.net/qq_42405688/article/details/124732195