Concatenation operator (+) vs. concat() [duplicate

2019-01-14 15:08发布

This question already has an answer here:

For string concatenation we can use either the concat() or concat operator (+).

I have tried the following performance test and found concat() is faster and a memory efficient way for string concatenation.

String concatenation comparison for 100,000 times:

String str = null;

//------------Using Concatenation operator-------------
long time1 = System.currentTimeMillis();
long freeMemory1 = Runtime.getRuntime().freeMemory();

for(int i=0; i<100000; i++){
    str = "Hi";
    str = str+" Bye";
}
long time2 = System.currentTimeMillis();
long freeMemory2 = Runtime.getRuntime().freeMemory();

long timetaken1 = time2-time1;
long memoryTaken1 = freeMemory1 - freeMemory2;
System.out.println("Concat operator  :" + "Time taken =" + timetaken1 +
                   " Memory Consumed =" + memoryTaken1);

//------------Using Concat method-------------
long time3 = System.currentTimeMillis();
long freeMemory3 = Runtime.getRuntime().freeMemory();
for(int j=0; j<100000; j++){
    str = "Hi";
    str = str.concat(" Bye");
}
long time4 = System.currentTimeMillis();
long freeMemory4 = Runtime.getRuntime().freeMemory();
long timetaken2 = time4-time3;
long memoryTaken2 = freeMemory3 - freeMemory4;
System.out.println("Concat method  :" + "Time taken =" + timetaken2 +
                   " Memory Consumed =" + memoryTaken2);

Result

Concat operator: Time taken = 31; Memory Consumed = 2259096
Concat method  : Time taken = 16; Memory Consumed = 299592

If concat() is faster than the operator then when should we use concatenation operator (+)?

8条回答
戒情不戒烟
2楼-- · 2019-01-14 16:05

In general it is a bad practice to concatenate Strings with + and with concat(). If you want to create a String use StringBuilder instead.

查看更多
Bombasti
3楼-- · 2019-01-14 16:09

Though both the operator and the method are giving the same output, the way they work internally differs.

The concat() method that just concatenates str1 with str2 and outputs a string, is more efficient for a small number of concatenations.

But with concatenation operator '+', str1+=str2; will be interpreted as str1 = new StringBuilder().append(str1).append(str2).toString();

You can use the concat method when using a fewer number of strings to concatenate. But the StringBuilder method would be fast in terms of performance, if you are using a large number of strings.

查看更多
登录 后发表回答