这几天在处理sonar扫出来的代码问题,有一些觉得还是有必要写下来的,所以做一些记录。每次记录2个。
1、loop中请不要用+来操作字符串,建议用StringBuilder。
Strings should not be concatenated using '+' in a loop
Strings are immutable objects, so concatenation doesn't simply add the new String to the end of the existing string. Instead, in each loop iteration, the first String is converted to an intermediate object type, the second string is appended, and then the intermediate object is converted back to a String. Further, performance of these intermediate operations degrades as the String gets longer. Therefore, the use of StringBuilder is preferred.
目前Java中连接字符串有如下五种方式:+、concat、org.apache.commons.lang3.StringUtils.join、StringBuffer(线程安全)、StringBuilder(线程不安全)。其实大家可以做个简单的对比,StringBuilder是最快的。
2、equals方法推荐把常量放左边,变量放右边
Strings literals should be placed on the left side when checking for equality
It is preferable to place string literals on the left-hand side of anequals()orequalsIgnoreCase()method call.
网友评论