Java – there is a faster method, and then StringBuilder can connect strings in up to 9-10 steps?
•
Java
I have this code to connect 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; }
The important thing is that the array can hold up to 10 items, so it's not much
My trace output tells me that this method is called 18864 times and takes 16% of the running time Can I optimize more?
Solution
Some ideas:
1) Do you initialize StringBuilder with the estimated maximum capacity? This saves time on internal array reallocation Copy
2) Maybe you can append a trailing comma to the loop and avoid the condition of string length in the loop Instead, add a single condition at the end of the method and remove the trailing comma if necessary
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码