1. 对于boolean值,避免不必要的等式判断
将一个boolean值与一个true比较是一个恒等操作(直接返回该boolean变量的值). 移走对于boolean的不必要操作至少会带来2个好处:
1)代码执行的更快 (生成的字节码少了5个字节);
2)代码也会更加干净 。
例子:
public class UEQ
{
boolean method (String string) {
return string.endsWith ("a") == true; // Violation
}
}
更正:
class UEQ_fixed
{
boolean method (String string) {
return string.endsWith ("a");
}
}
2. 使用StringBuffer代替String
当处理字符串的相加时,常见的写法是:..
String str1 = "Hello";
String str2 = "welcome to world";
String str3 = str1 + ", " + str2 +"!";
System.out.println(str3);
很多人都知道,这样的代码效率是很低的,因为String是用来存储字符串常量的,如果要执行“+”的操作,系统会生成一些临时的对象,并对这些对象进行管理,造成不必要的开销。
如果字符串有连接的操作,替代的做法是用StringBuffer类的append方法,它的缺省构造函数和append的实现是:
public StringBuffer() { // 构造函数
this(16); // 缺省容量16}
public synchronized StringBuffer append(String str) {
if (str == null) {
str = String.valueOf(str);
}
int len =str.length();
int newcount = count + len;
if(newcount > value.length)
expandCapacity(newcount);
// 扩充容量
str.getChars(0, len, value, count);
count = newcount;
return this;
}
当字符串的大小超过缺省16时,代码实现了容量的扩充,为了避免对象的重新扩展其容量,更好的写法为:
StringBuffer buffer = new StringBuffer(30);
// 分配指定的大小。
buffer.append("hello");
buffer.append(",");
buffer.append("welcometo world!");
String str = buffer.toString();
3. 用'StringTokenizer' 代替 'indexOf()' 和'substring()'
字符串的分析在很多应用中都是常见的。使用indexOf()和substring()来分析字符串容易导致StringIndexOutOfBoundsException。而使用StringTokenizer类来分析字符串则会容易一些,效率也会高一些。
例子:
public class UST {
void parseString(String string) {
int index = 0;
while ((index = string.indexOf(".", index)) != -1) {
System.out.println (string.substring(index, string.length()));
}
}
}
4。在字符串相加的时候,使用 ' ' 代替 " " ,如果该字符串只有一个字符的话
例子:
public class STR {
public void method(String s) {
String string = s + "d" // violation.
string = "abc" + "d" // violation.
}
}
更正:
将一个字符的字符串替换成' '
public class STR {
public void method(String s) {
String string = s + 'd'
string = "abc" + 'd'
}
}
5. 如果只是查找单个字符的话,用charAt()代替startsWith()
用一个字符作为参数调用startsWith()也会工作的很好,但从性能角度上来看,调用用String API无疑是错误的!
例子:
public class PCTS {
private void method(String s) {
if (s.startsWith("a")) { // violation
// ...
}
}
}
更正
将'startsWith()' 替换成'charAt()'.
public class PCTS {
private void method(String s) {
if ('a' == s.charAt(0)) {
// ...
}
}
}