[Java] Do not use "+" in append!

This is a sequel to Last Post.

Last time, I wrote that it is better to use the append method of StringBuilder when concatenation strings in Java.

However, I occasionally see code that misuses append.

Wrong use of append

For example, this code

StringBuilder sb = new StringBuilder();
String val = "hoge";
sb.append("[" + val + "]")

String concatenation using + creates a String object each time, which slows down the processing speed.

In this example, the String object has been created at the " [" + val +"] " part, so the processing speed will eventually slow down.

Improvement example

Let's do this

StringBuilder sb = new StringBuilder();
String val = "hoge";
sb.append("[").append(val).append("]");

Instead of connecting with +, connect using append multiple times.

So how much does the processing speed change before and after the improvement?

Verify the difference in processing speed

I compared the processing speed with the code below.

public class StringBuilderTest{
  public static void main(String[] args) {
    final int MAX_COUNT = 100;
    System.out.println("Number of joins:" + MAX_COUNT + "When");

    StringBuilder sb1 = new StringBuilder();
    StringBuilder sb2 = new StringBuilder();

    long resultTime1;
    long resultTime2;
    long startTime;
    long endTime;

    /*********************Before improvement: append()When performing string concatenation within*********************/
    //Start time
    startTime = System.nanoTime();

    for (int i = 0; i < MAX_COUNT; i++) {
      sb2.append(Integer.toString(i) + "\n");
    }
    //ending time
    endTime = System.nanoTime();

    //Calculate the time taken for processing
    resultTime1 = endTime - startTime;

    /*********************After improvement: append()When using twice*********************/
    //Start time
    startTime = System.nanoTime();

    //String concatenation with StringBuilder
    for (int i = 0; i < MAX_COUNT; i++) {
      sb1.append(Integer.toString(i)).append("\n");
    }
    //ending time
    endTime = System.nanoTime();

    //Time taken
    resultTime2 = endTime - startTime;

    System.out.println("① append()Processing time when joining is performed within:" + resultTime1 + "Nanoseconds");
    System.out.println("② append()Processing time when using twice:" + resultTime2 + "Nanoseconds");
    System.out.println("② is better" + (resultTime1 - resultTime2) + "Nanoseconds fast");
  }
}

It is a program that compares the difference in processing speed when character string concatenation is performed 100 times.

The result is below.

スクリーンショット 2018-07-21 19.11.21.png

It's faster to use ʻappend` twice.

at the end

Actually, this article is a reprint from the blog. I also post about other things on my blog.

** Memorandum of scribbles of SE in the first year of working people-Hatena Blog **

Recommended Posts

[Java] Do not use "+" in append!
Do you use Stream in Java?
Do not use instance variables in partial
Do not declare variables in List in Java
Use OpenCV in Java
Use PreparedStatement in Java
Use Redis Stream in Java
Do not write if (isAdmin == true) code in Java
[Java] [Spring] [Spring Batch] Do not create / use Spring Batch metadata table
Do Scala Option.or Null in Java
Do HelloWorld in Java / IntelliJ / Gradle
Let's use Twilio in Java! (Introduction)
Use composite keys in Java Map.
How to use classes in Java?
Use OpenCV_Contrib (ArUco) in Java! (Part 2-Programming)
[Java] Use cryptography in the standard library
Use "Rhino" which runs JavaScript in Java
Do not accept System.in in gradle run
Do not return when memoizing in Ruby
Do TensorFlow in Java. It's easy, though. .. .. ..
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
[Java] Use Collectors.collectingAndThen
Pi in Java
FizzBuzz in Java
Use OpenCV_Contrib (ArUco) in Java! (Part 1-Build) (OpenCV-3.4.4)
[Java] Use of final in local variable declaration
Solution for NetBeans 8.2 not working in Java 9 environment
Support for CheckStyle "Do not use inline conditions"
[JAVA] [Spring] [MyBatis] Use IN () with SQL Builder
Why use setters/getters instead of public/private in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Make "I'm not a robot" in Java EE (Jakarta EE)
Constraint programming in Java
Put java8 in centos7
I want to do something like "cls" in Java
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Use java.time in Jackson
Comments in Java source
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Use Interceptor in Spring
Hello World in Java
webApi memorandum in java
Type determination in Java
I dealt with Azure Functions not working in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java