本文簡單介紹一下在寫代碼過程中用到的一些讓JAVA代碼更高效的技巧。
1,將一些系統(tǒng)資源放在池中,如數(shù)據(jù)庫連接,線程等.在standalone的應(yīng)用中,數(shù)據(jù)庫連接池可以使用一些開源的連接池實現(xiàn),如C3P0,proxool和DBCP等,在運行在容器中的應(yīng)用這可以使用服務(wù)器提供的DataSource.線程池可以使用JDK本身就提供的java.util.concurrent.ExecutorService.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; public class JavaThreadPool { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(2); Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.shutdown(); } } class MyThread extends Thread { public void run() { System.out.println(Thread.currentThread().getName() + "running...."); } } |
2,減少網(wǎng)絡(luò)開銷,在和數(shù)據(jù)庫或者遠程服務(wù)交互的時候,盡量將多次調(diào)用合并到一次調(diào)用中。
3,將經(jīng)常訪問的外部資源cache到內(nèi)存中,簡單的可以使用static的hashmap在應(yīng)用啟動的時候加載,也可以使用一些開源的cache框架,如OSCache和Ehcache等.和資源的同步可以考慮定期輪詢和外部資源更新時候主動通知.或者在自己寫的代碼中留出接口(命令方式或者界面方式)共手動同步。
4,優(yōu)化IO操作,JAVA操作文件的時候分InputStream and OutputStream,Reader and Writer兩類,stream的方式要快,后者主要是為了操作字符而用的,在字符僅僅是ASCII的時候可以用stream的方式提高效率.JDK1.4之后的nio比io的效率更好。
1
2
3
4
|
OutputStream out = new BufferedOutputStream( new FileOutputStream( new File( "d:/temp/test.txt" ))); out.write( "abcde" .getBytes()); out.flush(); out.close(); |
利用BufferedInputStream,BufferedOutputStream,BufferedReader,BufferedWriter減少對磁盤的直接訪問次數(shù)。
1
2
3
|
FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); while (br.readLine() != null ) count++; |
5不要頻繁的new對象,對于在整個應(yīng)用中只需要存在一個實例的類使用單例模式.對于String的連接操作,使用StringBuffer或者StringBuilder.對于utility類型的類通過靜態(tài)方法來訪問。
6,避免使用錯誤的方式,如Exception可以控制方法推出,但是Exception要保留stacktrace消耗性能,除非必要不要使用instanceof做條件判斷,盡量使用比的條件判斷方式.使用JAVA中效率高的類,比如ArrayList比Vector性能好。
7,對性能的考慮要在系統(tǒng)分析和設(shè)計之初就要考慮。
總之,一個系統(tǒng)運行時的性能,無非是從CPU,Memory和IO這三個主要方面來考慮優(yōu)化.減少不必要的CPU消耗,減少不必要的IO操作,增加Memory利用效率。