在循環條件中使用複雜表達式
在不作編譯優化的狀況下,在循環中,循環條件會被反覆計算,若是不使用複雜表達式,而使循環條件值不變的話,程序將會運行的更快。
例子:
import java.util.Vector;
class CEL {
void method (Vector vector) {
for (int i = 0; i < vector.size (); i++) // Violation
; // ...
}
}
更正:
class CEL_fixed {
void method (Vector vector) {
int size = vector.size ()
for (int i = 0; i < size; i++)
; // ...
}
}
2、爲'Vectors' 和 'Hashtables'定義初始大小
JVM爲Vector擴充大小的時候須要從新建立一個更大的數組,將原原先數組中的內容複製過來,最後,原先的數組再被回收。可見Vector容量的擴大是一個頗費時間的事。
一般,默認的10個元素大小是不夠的。你最好能準確的估計你所須要的最佳大小。
例子:
import java.util.Vector;
public class DIC {
public void addObjects (Object[] o) {
// if length > 10, Vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o); // capacity before it can add more elements.
}
}
public Vector v = new Vector(); // no initialCapacity.
}
更正:
本身設定初始大小。
public Vector v = new Vector(20);
public Hashtable hash = new Hashtable(10);
參考資料:
Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming
Techniques" Addison Wesley, ISBN: 0-201-70429-3 pp.55 – 57
3、在finally塊中關閉Stream
程序中使用到的資源應當被釋放,以免資源泄漏。這最好在finally塊中去作。無論程序執行的結果如何,finally塊老是會執行的,以確保資源的正確關閉。
例子:
import java.io.*;
public class CS {
public static void main (String args[]) {
CS cs = new CS ();
cs.method ();
}
public void method () {
try {
FileInputStream fis = new FileInputStream ("CS.java");
int count = 0;
while (fis.read () != -1)
count++;
System.out.println (count);
fis.close ();
} catch (FileNotFoundException e1) {
} catch (IOException e2) {
}
}
}
更正:
在最後一個catch後添加一個finally塊
參考資料:
Peter Haggar: "Practical Java - Programming Language Guide".
Addison Wesley, 2000, pp.77-79
4、使用'System.arraycopy ()'代替經過來循環複製數組
'System.arraycopy ()' 要比經過循環來複制數組快的多。
例子:
public class IRB
{
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 = i;
}
int[] array2 = new int [100];
for (int i = 0; i < array2.length; i++) {
array2 = array1 ; // Violation
}
}
}java