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)) {
// ...
}
}
}