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 (+)
?
In general it is a bad practice to concatenate Strings with
+
and withconcat()
. If you want to create a String useStringBuilder
instead.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 asstr1 = 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.