Some times we just need to concat some strings “nouns”;
When we deal with a few amount of data, this task is very simple. We can just add the firstString with the secondString;
Sample 1:
String firstString = “Fisrt Name”;
String secondString = “Last Name”;
String finalString = firstString + secondString;
System.out.println(finalString);
But, some times it is necessary to concat a large amount of data, using a looping or something else;
Sample 2:
String s1 = “Numbers separated by comma: “;
String s2 = “”;
String s3 = “”;
for (int i = 0; i <= size; i++) {
s2 = s2 + i + “, “;
}
s3 = s1 + s2;
When we deal with a large amount of data we need to take into consideration the performance of the algorithm;
On our sample 1 and sample 2 the JVM(java virtual machine) is going to create one new object for each concatenation and this may turn into a real problem when we have to concat a large amount of data.
Ok, this is a problem… But how can we do that without create a new object for each concatenation?
Answer:
There is an object to deal with this type of problem, it is called “StringBuilder” and we can use it’s native method called “append“, this method receaves as parameter the new string with you intend to concat.
Sample 3:
String s1 = “Numbers separated by comman: “;
StringBuilder s2 = new StringBuilder();
String s3 = “”;
for (int i = 0; i <= size; i++) {
s2.append(i).append(“, “);
}
s3 = s1 + s2;
Our focus is on performance, so, let’s see some results:
400 numbers:
Appending strings: 1ms
Adding strings: 1ms
4000 numbers:
Appending strings: 2ms
Adding strings: 45ms
40000 numbers:
Appending strings: 7ms
Adding strings: 4342ms
Analysing these number we may see that:
With 400 numbers both result need the same amount of time to execute;
With 4000 numbers the use of the append method is 22 times faster than adding strings;
With 40000 numbers the use of the append method is 620 times faster than adding strings;
Try it for your self – get the code on the github repository.
Congratulations @namom! You have received a personal award!
1 Year on Steemit
Click on the badge to view your Board of Honor.