0
点赞
收藏
分享

微信扫一扫

pmd检测出的代码效率的比较和总结【转】


java项目测试

以下是我在检查项目pmd的时候积累下来的,和大家分享下,呵呵。
1:
Use equals() to compare strings instead of '==' or '!='
解释:
使用equals()比较,而不是字符串'=='或'!='
2:
String.indexOf(‘char’)的速度比String.indexOf(“字符串”)。
解释:
比如String.indexOf('d')的速度就比String.indexOf("d")要快

3:
Avoid if (x != y) ..; else ..;
解释:
pmd说避免把判断非摆在前面,这样会引起阅读混淆,要判断的话,就把 == 的放在前面,掉转下就好的,容易读和理解。

4:
x.equals("2"); // should be "2".equals(x)
that way if the String is null you won't get a NullPointerException, it'll just return false

解释:
如果参数在前面,如果参数是空的话,程序会抛出NullPointerException,所以
应该把确定的字符串放在前面,把参数放在括号里面


5
建议:Substitute calls to size() == 0 (or size() != 0) with calls to isEmpty()

意思是说对List类的if(list.size()==0),建议使用isEmpty()来操作

6

if (Integer.parseInt(newInput) == 0) 

{ 

return true; 

} else 

{ 

return false; 

}



没有必要为一个返回true和false的行为做if else 直接
eturn Integer.parseInt(newInput) == 0 就行了

7:

public class Foo { 

 public int foo() { 

 int x = doSomething(); 

 return x; // instead, just 'return doSomething();' 

 } 

 }



Avoid unnecessarily creating local variables


如果只是返回doSomething的返回值,就没必要在弄一个实体了


8:
String.trim()。长度()== 0是一种低效的方法来验证一个空字符串。


9:

public class Foo { 

 private int x; //Why bother saving this? 

 public void foo(int y) { 

 x = y + 5; 

 return x; 

 } 

}




如果x只用于foo这个方法。那么。建议放在foo里面当局部变量不要做全局变量了

10:
用equals来判断好过 ==

11:
判空用isEmpty

12
private List<MenuFunction> menuFunctionList = new ArrayList<MenuFunction>();
而不要
private ArrayList<MenuFunction> menuFunctionList = new ArrayList<MenuFunction>();

好像是说更支持多态吧。我也不知道,感觉大吃小总比小吃小好。List吃Arraylist.

举报

相关推荐

0 条评论