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.
outputto a string on each iteration, and uses string concatenation. You definitely don't want to do that.