Namom Alencar avatar

Best way to concat String – JAVA

namom

Published: 04 Jun 2018 › Updated: 04 Jun 2018Best way to concat String – JAVA

Best way to concat String – JAVA

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.

Leave Best way to concat String – JAVA to:

Written by

I'm software developer, passionate for new technologies.

Read more #java posts


Best Posts From Namom Alencar

We have not curated any of namom's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Namom Alencar