Description
SBSC: Method AppletComponent.getValue(String) concatenates strings using + in a loop
The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration.
使用loop連接字串時,是使用+,會造成不必要的物件轉換。
Solution
Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly.
透過StringBuffer將字串連接起來,再轉回String即可。
Example
Before:
return a + b + c;
After:
StringBuffer sb = new StringBuffer(); sb.append(a); sb.append(b); sb.append(c); return sb.toString();
留言
張貼留言