java學習

          java學習

           

          java程序性能優化

          一、避免在循環條件中使用復雜表達式 在不做編譯優化的情況下,在循環中,循環條件會被反復計算,如果不使用復雜表達式,而使循環條件值不變的話,程序將會運行的更快。 例子: 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++) ; //  } }
          二、為'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);

          三、在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 = 0while (fis.read () != -1) count++; system.out.println (count); fis.close (); } catch (filenotfoundexception e1) { } catch (ioexception e2) { } } } 更正: 在最后一個catch后添加一個finally塊

          四、使用'system.arraycopy ()'代替通過來循環復制數組 'system.arraycopy ()' 要比通過循環來復制數組快的多。 例子: public class irb { void method () { int[] array1 = new int [100]; for (int i = 0; i < array1.length; i++) { array1 [i] = i; } int[] array2 = new int [100]; for (int i = 0; i < array2.length; i++) { array2 [i] = array1 [i]; // violation } } } 更正: public class irb{ void method () { int[] array1 = new int [100]; for (int i = 0; i < array1.length; i++) { array1 [i] = i; } int[] array2 = new int [100]; system.arraycopy(array1, 0, array2, 0, 100); } }

          五、讓訪問實例內變量的getter/setter方法變成”final” 簡單的getter/setter方法應該被置成final,這會告訴編譯器,這個方法不會被重載,所以,可以變成”inlined” 例子: class maf { public void setsize (int size) { _size = size; } private int _size; } 更正: class daf_fixed { final public void setsize (int size) { _size = size; } private int _size; }

          posted on 2013-02-22 14:06 楊軍威 閱讀(219) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 通河县| 乌兰县| 娄底市| 普兰县| 汉中市| 大渡口区| 新宾| 翁牛特旗| 双流县| 扶风县| 乳源| 桐庐县| 界首市| 崇明县| 沙田区| 正定县| 娱乐| 高雄县| 华亭县| 保康县| 额济纳旗| 双鸭山市| 张北县| 阿图什市| 天峻县| 孝昌县| 红桥区| 凤庆县| 苍山县| 和平区| 洪雅县| 乐陵市| 麻栗坡县| 太仓市| 诸城市| 独山县| 鸡东县| 石台县| 柳州市| 新田县| 陆良县|