简体   繁体   中英

Does concatenating in a StringBuilder append() statement take a different amount of execution time than using two append() statements?

I was wondering the execution speed changes if a programmer concatenates inside a Stringbuilder append() statement, or just uses two append statements instead of one.

I am asking this question to help me figure out why we use the StringBuilder class at all when we can just concatenate.

Concatenation Example:

public class MCVE {

    public static void main(String[] args) {
        String[] myArray = {"Some", "stuff", "to", "append", "using", "the",
                "StringBuilder", "class's", "append()", "method"};

        StringBuilder stringBuild = new StringBuilder();

        for(String s: myArray) {
            stringBuild.append(s + " ");
        }

    }
}

Double-Append() Example:

public class MCVE {

    public static void main(String[] args) {
        String[] myArray = {"Some", "stuff", "to", "append", "using", "the",
                "StringBuilder", "class's", "append()", "method"};

        StringBuilder stringBuild = new StringBuilder();

        for(String s: myArray) {
            stringBuild.append(s);
            stringBuild.append(" ");
        }

    }
}

In theory, yes, the concatenation version will take longer, because under the covers it creates a whole new StringBuilder , appends s , appends " " , and then uses toString to create(!) a string for that to pass to the append you coded. (That's what the compiler does. To know about your specific situation, you'd need to test a benchmark representative of your actual code. After all, the JIT will get involved if it's a hotspot at runtime.)

Of course, you probably won't notice. But still, if you're already using StringBuilder , use it (by doing append twice instead). :-)


(The first paragraph above wouldn't be true if they were both string literals, eg "foo" + "bar" . The compiler does that concatenation.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM