標籤:
1. 什麼是好的代碼?
高效正確
便於維護
簡潔清晰
2. 如何做?
讓代碼比你來時更乾淨
做有意義的命名
別重複自己
注意代碼工整
記住:不要把自己當程式員,要把自己當成藝術家,出自你手的代碼都是一件藝術品,盡量讓她優雅。
3.原則
第一條,關於注釋和文檔
好的代碼不需要注釋和文檔(不包括設計文檔)。
我們要做的,盡量讓你的代碼簡單易懂,如果實在做不到,一定添加簡單易懂的注釋文字。不要繁瑣的長篇大論。
記住:代碼裡一切注釋和文檔都是浮雲。
第二條,關於代碼結構
不要為了實現需求不停的堆代碼,講究下技巧
多用物件導向和面向介面編程,以提高代碼的擴充性和可維護性
多用用設計模式,以提高代碼的可閱讀性和靈活性,避免重複你的代碼
記住:簡單,優雅,清晰的代碼是最能減輕工作量和減少出現問題的方法。
第三條,關於測試
如果可能,盡量讓你所有的方法都有測試代碼
如果可能,應用測試驅動開發
如果可能,盡量在發布程式的之前運行測試案例並保證沒有問題
記住:沒有測試的代碼都是浮雲
4. Tips
1.避免重複初始化。
test1
HashMap map = new HashMap();
public Test1(){
// map = new HashMap();
}
public static void main(String[] args) {
int TT = 1000000;
long t1 = System.currentTimeMillis();
for(int i=TT; i>=0; --i) {
Test1 t = new Test1();
}
System.out.println(System.currentTimeMillis()-t1);
}
重複初始化時間:187 172
正常初始化時間: 94 93
test2
public final static int max(int a, int b) {
return (a>b)? a:b;
}
public static void main(String[] args) {
final int TT = 1000000;
int a = 5, b=10;
int c;
long t1 = System.currentTimeMillis();
for(int i=TT; i>=0; --i) {
c = max(a, b);
}
System.out.println(System.currentTimeMillis()-t1);
long t2 = System.currentTimeMillis();
for(int i=TT; i>=0; --i) {
c = (a>b)? a:b;
}
System.out.println(System.currentTimeMillis()-t2);
}
final 方法會使用內聯方式進行編譯,這樣會提高效能,不過貌似新的JVM做了最佳化,第一次運行時會慢一些,以後非final和final效能差不多。
test3
NewObject object=new NewObject();
int value;
if(i>0) {
value=object.getValue();
}
最佳化後:
int value;
if(i>0){
NewObject object = new NewObject();
Value = object.getValue();
}
就近原則,盡量採用Lazy loading策略,減少記憶體開銷
test4
List?alist=uSvr.getUserinfoList();
for(int i=0;i<alist.size();i++){
。。。
}
最佳化後:
for(int i=0,p=alist.size();i<p;i++){
。。。
}
迴圈操作時,盡量使用局部變數,減少記憶體定址時間
15 16
0 0
test5
long t1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
Test1 t = new Test1();
}
System.out.println(System.currentTimeMillis() - t1);
long t2 = System.currentTimeMillis();
Test1 t = null;
for (int i = 0; i < 10000000; i++) {
t = new Test1();
}
System.out.println(System.currentTimeMillis() - t2);
減少迴圈New變數的操作,這種做法會在記憶體中儲存N份這個對象的引用,會浪費大量的記憶體空間,增加GC
64 63
47 47
test6
避免在做最終條件比較時採用方法傳回值的方式進行判斷,這樣做將增大系統開銷,降低效能
while(isTrue()) {
...
}
最佳化後:
boolean isTrue= isTrue();
while(isTrue) {
...
}
test7
盡量避免在迴圈體中使用try-catch塊,最好在迴圈體外進行try-cache以提高效能
do{
try{
...
} catch(Exception e){ }
}while(isTrue)
最佳化後
try{
do {
...
}while(isTrue)
}catch(Exception e){}
test8
在多重迴圈中,如果有可能,盡量將最他的迴圈放在最內層,最短迴圈放在最外層,以減少迴圈切換次數。
for (int i=0; i<100000; i++) {
for(int j=0; j<10; j++) {
...
}
}
最佳化後:
for (int j=0; j<10; j++) {
for(int i=0; i<100000; i++) {
...
}
}
test9
迴圈內有If-else類邏輯,最好將if-else邏輯判斷移到迴圈體外,以提高效能。
for(int i=0; i<100000; i++)
if(isTrue){
doThis
} else {
doThat
}
}
最佳化後:
if(isTrue) {
for(int i=0; i<100000;i++) {
doThis
}
} else {
for(int i=0; i<100000;i++) {
doThat
}
}
java代碼最佳化