Sonar相关规则解读1

这几天在处理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.


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容