lukas22497 lukas22497 - 5 months ago 11
Java Question

Building string from file content (concatenating array) is slow

I have a program reading 100,000 lines of a file. I have to evaluate measurement data.

With BufferedReader I load the content in an array. After this I want to display the content in a textarea in my GUI using this code:

String uiFileContent = "";
for (int j = 0; j < file.length; j++) {
uiFileContent += file[j];
System.out.println("linenumber:\t" + j);
}

txtAreaFile.setText(dateiinhaltString);


This code is so slow. In Eclipse I can see that the loop is at line 30,000 after 5 minutes.

How is it possible to optimize this operation?

Answer

One reason why your code is slow is because you are concatenating String objects in a loop. This is going to copy everything you have read so far into a new String with every iteration in the loop.

After iteration 1, uiFileContent will contain line 1.

In the second iteration, it will copy line 1 and line 2 into a new String.

In the third iteration, it will copy line 1, line 2 and line 3 into a new String.

...

In the 80,000th iteration, it will copy line 1, line 2, line 3, ..., line 79,999 and line 80,000 into a new String.

This is very inefficient.

Use a StringBuilder instead to avoid all this copying:

StringBuilder builder = new StringBuilder();
try (BufferedReader in = new BufferedReader(new FileReader("myfile.txt"))) {
    String line;
    while ((line = in.readLine()) != null) {
        builder.append(line).append('\n');
    }
}

String uiFileContent = builder.toString();