title:JAVA程式效能調優筆記(3)-有助於改善效能的技巧
tags: 有助於改善效能的技巧 grammar_cjkRuby: true 1.慎用異常
@Test public void testInForTryCatch() {//效能差 long starttime=System.currentTimeMillis(); int a=0; for(int i=0;i<100000000;i++){ try{ a++; }catch(Exception e){ } } long endtime=System.currentTimeMillis(); System.out.println("testInForTryCatch:"+(endtime-starttime)); } @Test public void testOutForTryCatch() {//效能好 long starttime=System.currentTimeMillis(); int a=0; try{ for(int i=0;i<100000000;i++){ a++; } }catch(Exception e){ } long endtime=System.currentTimeMillis(); System.out.println("testOutForTryCatch:"+(endtime-starttime)); }2.使用局部變數
局部變數的訪問速度遠遠高於類的成員變數
@Test public void testLocalVar() { long starttime=System.currentTimeMillis(); int a=0; for(int i=0;i<100000000;i++){ a++; } long endtime=System.currentTimeMillis(); System.out.println("testLocalVar:"+(endtime-starttime)); } @Test privat static int ta = 0; public void testMemberVar() { long starttime=System.currentTimeMillis(); for(int i=0;i<100000000;i++){ ta++; } long endtime=System.currentTimeMillis(); System.out.println("testMemberVar:"+(endtime-starttime)); } 3.位元運算代替乘除法
老生常談,能搞這個的人不多。
位元運算的常見操作和題目
一種經典位元運算的規則 4.替換switch(jdk1.7以上版本switch效能以糾正) 5.一維數組代替二維數組
如果將 array.length 提出來,特別是對二維數組則有很好的最佳化效果。 6.提取運算式
@Test public void testWeitiqu(){ double d=Math.random(); double a=Math.random(); double b=Math.random(); double e=Math.random(); double x,y; long starttime=System.currentTimeMillis(); for(int i=0;i<10000000;i++){ x=d*a*b/3*4*a; y=e*a*b/3*4*a;//重複應該抽象 } long endtime=System.currentTimeMillis(); System.out.println("testWeitiqu:"+(endtime-starttime)); } @Test public void testTiqu(){ double d=Math.random(); double a=Math.random(); double b=Math.random(); double e=Math.random(); double t,x,y; long starttime=System.currentTimeMillis(); for(int i=0;i<10000000;i++){ t=a*b/3*4*a; x=d*t; //抽象後 速度有很高提升 y=e*t; } long endtime=System.currentTimeMillis(); System.out.println("testTiqu:"+(endtime-starttime)); }7.展開迴圈
顧名思義,通過方法減少迴圈次數,有效降低時間。 8.布爾運算代替位元運算
我們很少用位元運算,所以瞭解一下即可。 9.使用arrayCopy()
@Test public void testArrayCopySystem(){ int size=100000; int[] array=new int[size]; int[] arraydst=new int[size]; for(int i=0;i<array.length;i++){ array[i]=i; } long starttime=System.currentTimeMillis(); for(int k=0;k<1000;k++) System.arraycopy(array, 0, arraydst, 0, size); long endtime=System.currentTimeMillis(); System.out.println("testArrayCopySystem:"+(endtime-starttime)+" last:"+arraydst[size-1]); }10.使用clone()代替 new
使用在大對象上面,小對象用new足可以了。可以參考一下Java複製技術 11.靜態方法代替執行個體方法
靜態方法明顯快與執行個體方法。