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.
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.
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?
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.
It's faster to use ʻappend` twice.
Actually, this article is a reprint from the blog. I also post about other things on my blog.
Recommended Posts