I have this code to concate some array elements:
StringBuilder sb = new StringBuilder();
private RatedMessage joinMessage(int step, boolean isresult) {
sb.delete(0, sb.length());
RatedMessage rm;
for (int i = 0; i <= step; i++) {
if (mStack[i] == null)
continue;
rm = mStack[i].getCurrentMsg();// msg is built upfront, this just returns, it's a getter method call
if (rm == null || rm.msg.length() == 0)
continue;
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(rm.msg);
}
rm.msg=sb.toString();
return rm;
}
Important the array holds max 10 items, so it's not quite much.
My trace output tells me this method is called 18864 times, 16% of the runtime was spent in this method. Can I optimize more?
First of all I won't reuse StringBuilder and always create new instance. That will be certainly faster, because it would allow GC to use young generation heap area.
Another little trick that allows to eliminate at least one if statement is to rewrite your code like this:
String separator = "";
for (int i = 0; i <= step; i++) {
...
sb.append(separator);
sb.append(rm.msg);
separator = ", ";
}
some ideas:
1) Do you initialize the StringBuilder with the estimated max capacity? This can save the time spent in the inner array re-allocation & copying.
2) Maybe you can append a trailing comma in the loop, and avoid the condition for string length inside the loop. Instead, add a single condition at the end of the method, and remove the trailing comma if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With