Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a faster method then StringBuilder for a max 9-10 step string concatenation?

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?

like image 219
Pentium10 Avatar asked May 25 '10 20:05

Pentium10


2 Answers

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 = ", ";
    }
like image 120
Eugene Kuleshov Avatar answered Nov 04 '22 04:11

Eugene Kuleshov


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.

like image 21
Eyal Schneider Avatar answered Nov 04 '22 03:11

Eyal Schneider