String and StringBuider for Everybody!

Hey! Are you one of the millions enthusiasts of String? Are you always doing something like str += “concatenate another string”?

Pretty good! Uh… unfortunately I’m joking, but calm down. I do the diagnosis and provide you the medicines too.

I explain: it turns out that a String object is immutable (each time you do “+=” you create another String object, with huge impact in processing time), while a StringBuilder is mutable and, because of that, far more efficient for that purpose.

Use the String class when you need to store immutable data to be read later, like names, addresses, API endpoints, file paths… For all other cases (except multithreaded environments, where you might use StringBuffer), you’ll use StringBuilder.

I give you some examples.

Example 1: String concatenation

StringBuilder message = new StringBuilder("Hello");
message.append(" ");
message.append("World!");
System.out.println(message.toString());

Example 2: Building dynamic strings

StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{");
jsonBuilder.append("\"name\": \"John\",");
jsonBuilder.append("\"age\": 30");
jsonBuilder.append("}");

When you do a benchmarking test comparing String and StringBuilder, the results are awesome, as we see in the code below:

int n = 10000;
long startTime = System.nanoTime();
long endTime;

// Using String
String result = "";
for (int i = 0; i < n; i++) {
    result += "a";
}
endTime = System.nanoTime();
long durationString = endTime - startTime;

System.out.println("String concatenation took: " + durationString + " nanoseconds");

// Using StringBuilder
startTime = System.nanoTime();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
    sb.append("a");
}
String resultStringBuilder = sb.toString();
endTime = System.nanoTime();
long durationStringBuilder = endTime - startTime;

System.out.println("StringBuilder concatenation took: " + durationStringBuilder + " nanoseconds");

With the result as shown below:

Well, for today it’s enough! See you soon!

By Igor Magalhães Oliveira

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *