本文簡(jiǎn)單介紹一下在寫代碼過(guò)程中用到的一些讓JAVA代碼更高效的技巧。
1,將一些系統(tǒng)資源放在池中,如數(shù)據(jù)庫(kù)連接,線程等.在standalone的應(yīng)用中,數(shù)據(jù)庫(kù)連接池可以使用一些開源的連接池實(shí)現(xiàn),如C3P0,proxool和DBCP等,在運(yùn)行在容器中的應(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ù)庫(kù)或者遠(yuǎn)程服務(wù)交互的時(shí)候,盡量將多次調(diào)用合并到一次調(diào)用中。
3,將經(jīng)常訪問(wèn)的外部資源cache到內(nèi)存中,簡(jiǎn)單的可以使用static的hashmap在應(yīng)用啟動(dòng)的時(shí)候加載,也可以使用一些開源的cache框架,如OSCache和Ehcache等.和資源的同步可以考慮定期輪詢和外部資源更新時(shí)候主動(dòng)通知.或者在自己寫的代碼中留出接口(命令方式或者界面方式)共手動(dòng)同步。
4,優(yōu)化IO操作,JAVA操作文件的時(shí)候分InputStream and OutputStream,Reader and Writer兩類,stream的方式要快,后者主要是為了操作字符而用的,在字符僅僅是ASCII的時(shí)候可以用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減少對(duì)磁盤的直接訪問(wèn)次數(shù)。
1
2
3
|
FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); while (br.readLine() != null ) count++; |
5不要頻繁的new對(duì)象,對(duì)于在整個(gè)應(yīng)用中只需要存在一個(gè)實(shí)例的類使用單例模式.對(duì)于String的連接操作,使用StringBuffer或者StringBuilder.對(duì)于utility類型的類通過(guò)靜態(tài)方法來(lái)訪問(wèn)。
6,避免使用錯(cuò)誤的方式,如Exception可以控制方法推出,但是Exception要保留stacktrace消耗性能,除非必要不要使用instanceof做條件判斷,盡量使用比的條件判斷方式.使用JAVA中效率高的類,比如ArrayList比Vector性能好。
7,對(duì)性能的考慮要在系統(tǒng)分析和設(shè)計(jì)之初就要考慮。
總之,一個(gè)系統(tǒng)運(yùn)行時(shí)的性能,無(wú)非是從CPU,Memory和IO這三個(gè)主要方面來(lái)考慮優(yōu)化.減少不必要的CPU消耗,減少不必要的IO操作,增加Memory利用效率。