Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String building performance in Java

Tags:

java

string

I have a performance problem with String Handling. I have a log file (simple text file) that I have to manipulate and performa several changes in text.
So the program adds line by line in one huge String. Basically it do.

while (not_finished) { 
   // create new stringAdd; 
   stringResult=stringResult + stringAdd + "\n"; 
} 
// output to a textArea in window
textArea.setText(stringResult);

Now the performances for this is horrible, so I upgraded to StringBuilder

StringBuilder result= new StringBuilder();    
while (not_finished) { 
// create new stringAdd; 
result.append( stringAdd +"\n"); 
} 
// output to a textArea in window
textArea.setText(result.toString()); 

This is much faster. String once added to result will not be changed. The problem is not with the performances when there are more than 400,000 lines (one line has from 1 to 70 characters).

How to increase performances of building String? Do you have any idea?

like image 860
Demosten Avatar asked Feb 21 '26 15:02

Demosten


1 Answers

Two things can be improved. You are still concatenating strings inside the loop, so you can try:

result.append(stringAdd).append('\n'); 

If you know the size of the string beforehand, you can minimize the number of internal buffer resizing:

// expecting 30k characters:
StringBuilder result= new StringBuilder(30_000);    
like image 121
Thomas Jungblut Avatar answered Feb 24 '26 05:02

Thomas Jungblut