I need to repeatedly append strings (for about 50 times), which is a substring of another StringBuilder. I need to do this for around 30k inputs. It takes me a time of around 6 minutes.
StringBuilder input = new StringBuilder(10000);
StringBuilder output = new StringBuilder(10000);
//for loop till end of file which reads strings into variable 'input'
{
output.append(input.substring(1, 8));
output.append(input.substring(33, 45));
output.append(input.substring(20, 25)); // and so on
}
This took around 6 minutes.
So, i tried something like
{
output.append(input.substring(1, 8) + output.append(input.substring(33, 45) + output.append(input.substring20, 25) + .. // and so on );
}
This, has also taking the same time. I know both of these are same.
But, eventhough I use a StringBuilder, why still I have performance lag? Is there something I'm doing wrong?
I referred: StringBuilder vs String concatenation in toString() in Java and String concatenation in Java - when to use +, StringBuilder and concat and some more. Most of them suggest to use a StringBuilder.
You can definitely avoid creating so many objects using the overload of append
which allows you to specify a subsequence:
for (...)
{
output.append(input, 1, 8);
output.append(input, 33, 45);
output.append(input, 20, 25);
}
That may or may not help you. The string concatenation in your second example should definitely be avoided - I'm surprised that isn't making a huge difference... that suggests it may well not be the appending that's taking the time, but whatever's reading the input.
To test that, you should possibly try an empty for
loop, so that you're still reading all the same input, but not appending to output
at all.
See more on this question at Stackoverflow