Reputation:
Currently in my code I have something in a for loop similar to:
bstr = bstr + x.charAt(i) + x.charAt(i>>4) + x.charAt(i>>8);
Where i is an integer and the loop variable and x is a static final constant string of characters. bstr could be in the order of KBs.
Thanks
Upvotes: 0
Views: 2214
Reputation: 11113
A performant way to do this is to use a StringBuilder to concatenate your string:
StringBuilder builder = new StringBuilder();
for(int i = 0; i < count; i++){
builder.append(x.charAt(i));
builder.append(x.charAt(i>>4));
builder.append(x.charAt(i>>8));
}
return builder.toString();
This technique avoids the problem of storing all the copies of Strings between concatentations across the for loop.
edit:
or does this work for you (without adding chars one at a time):
StringBuilder builder = new StringBuilder();
for(int i = 0; i < count; i++){
builder.append(x);
}
return builder.toString();
Upvotes: 5
Reputation: 14554
One option is to use the StringBuilder
class. It has an internal array of char, which it appends your contents to until you call the toString
method, at which point it creates a new String
object. Of course, since it's using an array to store your characters, it may run out of space, at which point it will copy the contents into a new larger array. You can avoid that by initially giving it a capacity that will be large enough to hold the final String.
// Create a new StringBuilder with an initial capacity that is a little larger than the final String
StringBuilder builder = new StringBuilder(estimatedSizeOfFinalString);
int i = 0;
while (loopConditionIsTrue) {
builder.append(x.charAt(i)).append(x.charAt(i >> 4)).append(x.charAt(i >> 8);
}
String bstr = builder.toString();
Upvotes: 0
Reputation: 2503
Use a StringBuilder and just append while you're looping.
StringBuilder sb = new StringBuilder();
sb.append(bstr);
for(int i=0; i < somecondition; i++){
sb.append(x.charAt(i)).append(x.charAt(i>>4)).append(x.charAt(i>>8));
}
System.out.println(sb.toString());
Upvotes: 0
Reputation: 421130
Create a StringBuilder
before the loop and reuse it:
StringBuilder sb = new StringBuilder();
while (someCondition) {
...
sb.append(x.charAt(i))
.append(x.charAt(i >> 4))
.append(x.charAt(i >> 8));
...
}
bstr = sb.toString();
Upvotes: 1