JAVA & XML & JAVASCRIPT & AJAX & CSS

          Web 2.0 技術(shù)儲(chǔ)備............

            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            77 隨筆 :: 17 文章 :: 116 評(píng)論 :: 0 Trackbacks

          一、避免在循環(huán)條件中使用復(fù)雜表達(dá)式


          在不做編譯優(yōu)化的情況下,在循環(huán)中,循環(huán)條件會(huì)被反復(fù)計(jì)算,如果不使用復(fù)雜表達(dá)式,而使循環(huán)條件值不變的話,程序?qū)?huì)運(yùn)行的更快。

          例子:
          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擴(kuò)充大小的時(shí)候需要重新創(chuàng)建一個(gè)更大的數(shù)組,將原原先數(shù)組中的內(nèi)容復(fù)制過(guò)來(lái),最后,原先的數(shù)組再被回收。可見(jiàn)Vector容量的擴(kuò)大是一個(gè)頗費(fèi)時(shí)間的事。
          通常,默認(rèn)的10個(gè)元素大小是不夠的。你最好能準(zhǔn)確的估計(jì)你所需要的最佳大小。

          例子:
          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.
          }

          更正:
          自己設(shè)定初始大小。
          ????public Vector v = new Vector(20);??
          ????public Hashtable hash = new Hashtable(10);

          參考資料:
          Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming
          Techniques" Addison Wesley, ISBN: 0-201-70429-3 pp.55 – 57

          三、在finally塊中關(guān)閉Stream


          程序中使用到的資源應(yīng)當(dāng)被釋放,以避免資源泄漏。這最好在finally塊中去做。不管程序執(zhí)行的結(jié)果如何,finally塊總是會(huì)執(zhí)行的,以確保資源的正確關(guān)閉。
          ?????????
          例子:
          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 = 0;
          ????????????while (fis.read () != -1)
          ????????????????count++;
          ????????????System.out.println (count);
          ????????????fis.close ();
          ????????} catch (FileNotFoundException e1) {
          ????????} catch (IOException e2) {
          ????????}
          ????}
          }
          ?????????
          更正:
          在最后一個(gè)catch后添加一個(gè)finally塊

          參考資料:
          Peter Haggar: "Practical Java - Programming Language Guide".
          Addison Wesley, 2000, pp.77-79

          四、使用'System.arraycopy ()'代替通過(guò)來(lái)循環(huán)復(fù)制數(shù)組


          'System.arraycopy ()' 要比通過(guò)循環(huán)來(lái)復(fù)制數(shù)組快的多。
          ?????????
          例子:
          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);
          ????}
          }
          ?????????
          參考資料:
          http://www.cs.cmu.edu/~jch/java/speed.html

          五、讓訪問(wèn)實(shí)例內(nèi)變量的getter/setter方法變成”final”


          簡(jiǎn)單的getter/setter方法應(yīng)該被置成final,這會(huì)告訴編譯器,這個(gè)方法不會(huì)被重載,所以,可以變成”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;
          }

          參考資料:
          Warren N. and Bishop P. (1999), "Java in Practice", p. 4-5
          Addison-Wesley, ISBN 0-201-36065-9

          六、避免不需要的instanceof操作


          如果左邊的對(duì)象的靜態(tài)類型等于右邊的,instanceof表達(dá)式返回永遠(yuǎn)為true。
          ?????????
          例子:?????????
          public class UISO {
          ????public UISO () {}
          }
          class Dog extends UISO {
          ????void method (Dog dog, UISO u) {
          ????????Dog d = dog;
          ????????if (d instanceof UISO) // always true.
          ????????????System.out.println("Dog is a UISO");
          ????????UISO uiso = u;
          ????????if (uiso instanceof Object) // always true.
          ????????????System.out.println("uiso is an Object");
          ????}
          }
          ?????????
          更正:?????????
          刪掉不需要的instanceof操作。
          ?????????
          class Dog extends UISO {
          ????void method () {
          ????????Dog d;
          ????????System.out.println ("Dog is an UISO");
          ????????System.out.println ("UISO is an UISO");
          ????}
          }

          七、避免不需要的造型操作


          所有的類都是直接或者間接繼承自O(shè)bject。同樣,所有的子類也都隱含的“等于”其父類。那么,由子類造型至父類的操作就是不必要的了。
          例子:
          class UNC {
          ????String _id = "UNC";
          }
          class Dog extends UNC {
          ????void method () {
          ????????Dog dog = new Dog ();
          ????????UNC animal = (UNC)dog;??// not necessary.
          ????????Object o = (Object)dog;?????????// not necessary.
          ????}
          }
          ?????????
          更正:?????????
          class Dog extends UNC {
          ????void method () {
          ????????Dog dog = new Dog();
          ????????UNC animal = dog;
          ????????Object o = dog;
          ????}
          }
          ?????????
          參考資料:
          Nigel Warren, Philip Bishop: "Java in Practice - Design Styles and Idioms
          for Effective Java".??Addison-Wesley, 1999. pp.22-23

          八、如果只是查找單個(gè)字符的話,用charAt()代替startsWith()


          用一個(gè)字符作為參數(shù)調(diào)用startsWith()也會(huì)工作的很好,但從性能角度上來(lái)看,調(diào)用用String API無(wú)疑是錯(cuò)誤的!
          ?????????
          例子:
          public class PCTS {
          ????private void method(String s) {
          ????????if (s.startsWith("a")) { // violation
          ????????????// ...
          ????????}
          ????}
          }
          ?????????
          更正?????????
          將'startsWith()' 替換成'charAt()'.
          public class PCTS {
          ????private void method(String s) {
          ????????if ('a' == s.charAt(0)) {
          ????????????// ...
          ????????}
          ????}
          }
          ?????????
          參考資料:
          Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming
          Techniques"??Addison Wesley, ISBN: 0-201-70429-3

          九、使用移位操作來(lái)代替'a / b'操作


          "/"是一個(gè)很“昂貴”的操作,使用移位操作將會(huì)更快更有效。

          例子:
          public class SDIV {
          ????public static final int NUM = 16;
          ????public void calculate(int a) {
          ????????int div = a / 4;????????????// should be replaced with "a >> 2".
          ????????int div2 = a / 8;?????????// should be replaced with "a >> 3".
          ????????int temp = a / 3;
          ????}
          }

          更正:
          public class SDIV {
          ????public static final int NUM = 16;
          ????public void calculate(int a) {
          ????????int div = a >> 2;??
          ????????int div2 = a >> 3;
          ????????int temp = a / 3;???????// 不能轉(zhuǎn)換成位移操作
          ????}
          }

          十、使用移位操作代替'a * b'


          同上。
          [i]但我個(gè)人認(rèn)為,除非是在一個(gè)非常大的循環(huán)內(nèi),性能非常重要,而且你很清楚你自己在做什么,方可使用這種方法。否則提高性能所帶來(lái)的程序晚讀性的降低將是不合算的。

          例子:
          public class SMUL {
          ????public void calculate(int a) {
          ????????int mul = a * 4;????????????// should be replaced with "a << 2".
          ????????int mul2 = 8 * a;?????????// should be replaced with "a << 3".
          ????????int temp = a * 3;
          ????}
          }

          更正:
          package OPT;
          public class SMUL {
          ????public void calculate(int a) {
          ????????int mul = a << 2;??
          ????????int mul2 = a << 3;
          ????????int temp = a * 3;???????// 不能轉(zhuǎn)換
          ????}
          }

          十一、在字符串相加的時(shí)候,使用 ' ' 代替 " ",如果該字符串只有一個(gè)字符的話



          例子:
          public class STR {
          ????public void method(String s) {
          ????????String string = s + "d"??// violation.
          ????????string = "abc" + "d"??????// violation.
          ????}
          }

          更正:
          將一個(gè)字符的字符串替換成' '
          public class STR {
          ????public void method(String s) {
          ????????String string = s + 'd'
          ????????string = "abc" + 'd'???
          ????}
          }

          十二、不要在循環(huán)中調(diào)用synchronized(同步)方法


          方法的同步需要消耗相當(dāng)大的資料,在一個(gè)循環(huán)中調(diào)用它絕對(duì)不是一個(gè)好主意。

          例子:
          import java.util.Vector;
          public class SYN {
          ????public synchronized void method (Object o) {
          ????}
          ????private void test () {
          ????????for (int i = 0; i < vector.size(); i++) {
          ????????????method (vector.elementAt(i));????// violation
          ????????}
          ????}
          ????private Vector vector = new Vector (5, 5);
          }

          更正:
          不要在循環(huán)體中調(diào)用同步方法,如果必須同步的話,推薦以下方式:
          import java.util.Vector;
          public class SYN {
          ????public void method (Object o) {
          ????}
          private void test () {
          ????synchronized{//在一個(gè)同步塊中執(zhí)行非同步方法
          ????????????for (int i = 0; i < vector.size(); i++) {
          ????????????????method (vector.elementAt(i));???
          ????????????}
          ????????}
          ????}
          ????private Vector vector = new Vector (5, 5);
          }

          十三、將try/catch塊移出循環(huán)


          把try/catch塊放入循環(huán)體內(nèi),會(huì)極大的影響性能,如果編譯JIT被關(guān)閉或者你所使用的是一個(gè)不帶JIT的JVM,性能會(huì)將下降21%之多!
          ?????????
          例子:?????????
          import java.io.FileInputStream;
          public class TRY {
          ????void method (FileInputStream fis) {
          ????????for (int i = 0; i < size; i++) {
          ????????????try {??????????????????????????????????????// violation
          ????????????????_sum += fis.read();
          ????????????} catch (Exception e) {}
          ????????}
          ????}
          ????private int _sum;
          }
          ?????????
          更正:?????????
          將try/catch塊移出循環(huán)?????????
          ????void method (FileInputStream fis) {
          ????????try {
          ????????????for (int i = 0; i < size; i++) {
          ????????????????_sum += fis.read();
          ????????????}
          ????????} catch (Exception e) {}
          ????}
          ?????????
          參考資料:
          Peter Haggar: "Practical Java - Programming Language Guide".
          Addison Wesley, 2000, pp.81 – 83

          十四、對(duì)于boolean值,避免不必要的等式判斷


          將一個(gè)boolean值與一個(gè)true比較是一個(gè)恒等操作(直接返回該boolean變量的值). 移走對(duì)于boolean的不必要操作至少會(huì)帶來(lái)2個(gè)好處:
          1)代碼執(zhí)行的更快 (生成的字節(jié)碼少了5個(gè)字節(jié));
          2)代碼也會(huì)更加干凈 。

          例子:
          public class UEQ
          {
          ????boolean method (String string) {
          ????????return string.endsWith ("a") == true;???// Violation
          ????}
          }

          更正:
          class UEQ_fixed
          {
          ????boolean method (String string) {
          ????????return string.endsWith ("a");
          ????}
          }

          十五、對(duì)于常量字符串,用'String' 代替 'StringBuffer'


          常量字符串并不需要?jiǎng)討B(tài)改變長(zhǎng)度。
          例子:
          public class USC {
          ????String method () {
          ????????StringBuffer s = new StringBuffer ("Hello");
          ????????String t = s + "World!";
          ????????return t;
          ????}
          }

          更正:
          把StringBuffer換成String,如果確定這個(gè)String不會(huì)再變的話,這將會(huì)減少運(yùn)行開(kāi)銷提高性能。

          十六、用'StringTokenizer' 代替 'indexOf()' 和'substring()'


          字符串的分析在很多應(yīng)用中都是常見(jiàn)的。使用indexOf()和substring()來(lái)分析字符串容易導(dǎo)致StringIndexOutOfBoundsException。而使用StringTokenizer類來(lái)分析字符串則會(huì)容易一些,效率也會(huì)高一些。

          例子:
          public class UST {
          ????void parseString(String string) {
          ????????int index = 0;
          ????????while ((index = string.indexOf(".", index)) != -1) {
          ????????????System.out.println (string.substring(index, string.length()));
          ????????}
          ????}
          }

          參考資料:
          Graig Larman, Rhett Guthrie: "Java 2 Performance and Idiom Guide"
          Prentice Hall PTR, ISBN: 0-13-014260-3 pp. 282 – 283

          十七、使用條件操作符替代"if (cond) return; else return;" 結(jié)構(gòu)


          條件操作符更加的簡(jiǎn)捷
          例子:
          public class IF {
          ????public int method(boolean isDone) {
          ????????if (isDone) {
          ????????????return 0;
          ????????} else {
          ????????????return 10;
          ????????}
          ????}
          }

          更正:
          public class IF {
          ????public int method(boolean isDone) {
          ????????return (isDone ? 0 : 10);
          ????}
          }

          十八、使用條件操作符代替"if (cond) a = b; else a = c;" 結(jié)構(gòu)


          例子:
          public class IFAS {
          ????void method(boolean isTrue) {
          ????????if (isTrue) {
          ????????????_value = 0;
          ????????} else {
          ????????????_value = 1;
          ????????}
          ????}
          ????private int _value = 0;
          }

          更正:
          public class IFAS {
          ????void method(boolean isTrue) {
          ????????_value = (isTrue ? 0 : 1);???????// compact expression.
          ????}
          ????private int _value = 0;
          }

          十九、不要在循環(huán)體中實(shí)例化變量


          在循環(huán)體中實(shí)例化臨時(shí)變量將會(huì)增加內(nèi)存消耗

          例子:?????????
          import java.util.Vector;
          public class LOOP {
          ????void method (Vector v) {
          ????????for (int i=0;i < v.size();i++) {
          ????????????Object o = new Object();
          ????????????o = v.elementAt(i);
          ????????}
          ????}
          }
          ?????????
          更正:?????????
          在循環(huán)體外定義變量,并反復(fù)使用?????????
          import java.util.Vector;
          public class LOOP {
          ????void method (Vector v) {
          ????????Object o;
          ????????for (int i=0;i<v.size();i++) {
          ????????????o = v.elementAt(i);
          ????????}
          ????}
          }

          二十、確定 StringBuffer的容量


          StringBuffer的構(gòu)造器會(huì)創(chuàng)建一個(gè)默認(rèn)大小(通常是16)的字符數(shù)組。在使用中,如果超出這個(gè)大小,就會(huì)重新分配內(nèi)存,創(chuàng)建一個(gè)更大的數(shù)組,并將原先的數(shù)組復(fù)制過(guò)來(lái),再丟棄舊的數(shù)組。在大多數(shù)情況下,你可以在創(chuàng)建StringBuffer的時(shí)候指定大小,這樣就避免了在容量不夠的時(shí)候自動(dòng)增長(zhǎng),以提高性能。

          例子:?????????
          public class RSBC {
          ????void method () {
          ????????StringBuffer buffer = new StringBuffer(); // violation
          ????????buffer.append ("hello");
          ????}
          }
          ?????????
          更正:?????????
          為StringBuffer提供寢大小。?????????
          public class RSBC {
          ????void method () {
          ????????StringBuffer buffer = new StringBuffer(MAX);
          ????????buffer.append ("hello");
          ????}
          ????private final int MAX = 100;
          }
          ?????????
          參考資料:
          Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming
          Techniques" Addison Wesley, ISBN: 0-201-70429-3 p.30 – 31

          二十一、盡可能的使用棧變量


          如果一個(gè)變量需要經(jīng)常訪問(wèn),那么你就需要考慮這個(gè)變量的作用域了。static? local?還是實(shí)例變量?訪問(wèn)靜態(tài)變量和實(shí)例變量將會(huì)比訪問(wèn)局部變量多耗費(fèi)2-3個(gè)時(shí)鐘周期。
          ?????????
          例子:
          public class USV {
          ????void getSum (int[] values) {
          ????????for (int i=0; i < value.length; i++) {
          ????????????_sum += value[i];???????????// violation.
          ????????}
          ????}
          ????void getSum2 (int[] values) {
          ????????for (int i=0; i < value.length; i++) {
          ????????????_staticSum += value[i];
          ????????}
          ????}
          ????private int _sum;
          ????private static int _staticSum;
          }?????
          ?????????
          更正:?????????
          如果可能,請(qǐng)使用局部變量作為你經(jīng)常訪問(wèn)的變量。
          你可以按下面的方法來(lái)修改getSum()方法:?????????
          void getSum (int[] values) {
          ????int sum = _sum;??// temporary local variable.
          ????for (int i=0; i < value.length; i++) {
          ????????sum += value[i];
          ????}
          ????_sum = sum;
          }
          ?????????
          參考資料:?????????
          Peter Haggar: "Practical Java - Programming Language Guide".
          Addison Wesley, 2000, pp.122 – 125

          二十二、不要總是使用取反操作符(!)


          取反操作符(!)降低程序的可讀性,所以不要總是使用。

          例子:
          public class DUN {
          ????boolean method (boolean a, boolean b) {
          ????????if (!a)
          ????????????return !a;
          ????????else
          ????????????return !b;
          ????}
          }

          更正:
          如果可能不要使用取反操作符(!)

          二十三、與一個(gè)接口 進(jìn)行instanceof操作


          基于接口的設(shè)計(jì)通常是件好事,因?yàn)樗试S有不同的實(shí)現(xiàn),而又保持靈活。只要可能,對(duì)一個(gè)對(duì)象進(jìn)行instanceof操作,以判斷它是否某一接口要比是否某一個(gè)類要快。

          例子:
          public class INSOF {
          ????private void method (Object o) {
          ????????if (o instanceof InterfaceBase) { }??// better
          ????????if (o instanceof ClassBase) { }???// worse.
          ????}
          }

          class ClassBase {}
          interface InterfaceBase {}
          posted on 2006-06-02 14:33 Web 2.0 技術(shù)資源 閱讀(1574) 評(píng)論(1)  編輯  收藏 所屬分類: JAVA

          評(píng)論

          # re: Java程序性能優(yōu)化 ! 2007-01-13 16:05 q
          q  回復(fù)  更多評(píng)論
            

          主站蜘蛛池模板: 武夷山市| 崇阳县| 布拖县| 静宁县| 沁源县| 昌江| 昌都县| 庆安县| 伊川县| 兴海县| 抚松县| 虞城县| 大同县| 龙南县| 巫山县| 金阳县| 上林县| 溆浦县| 万载县| 阿荣旗| 台南市| 门源| 申扎县| 淅川县| 宁化县| 临漳县| 长寿区| 封丘县| 阜宁县| 云龙县| 汝州市| 麻阳| 黄山市| 荔波县| 东乌珠穆沁旗| 高陵县| 屏东市| 苏尼特左旗| 洪雅县| 壶关县| 鄂托克前旗|