java代码性能优化

 

一、避免在循环条件中使用复杂表达式 

在不做编译优化的情况下,在循环中,循环条件会被反复计算,如果不使用复杂表达式,而使循环条件值不变的话,程序将会运行的更快。 

例子: 

  1. import java.util.vector;  
  2. class cel {  
  3.     void method (vector vector) {  
  4.         for (int i = 0; i < vector.size (); i++)  // violation  
  5.             ; // ...  
  6.     }  
  7. }  
<span style="font-family:Arial;font-size:12px;">import java.util.vector;
class cel {
    void method (vector vector) {
        for (int i = 0; i < vector.size (); i++)  // violation
            ; // ...
    }
}
</span>

更正: 
  1. class cel_fixed {  
  2.     void method (vector vector) {  
  3.         int size = vector.size ()  
  4.         for (int i = 0; i < size; i++)  
  5.             ; // ...  
  6.     }  
  7. }  
<span style="font-family:Arial;font-size:12px;">class cel_fixed {
    void method (vector vector) {
        int size = vector.size ()
        for (int i = 0; i < size; i++)
            ; // ...
    }
}</span>


二、为'vectors' 和 'hashtables'定义初始大小 

jvm为vector扩充大小的时候需要重新创建一个更大的数组,将原原先数组中的内容复制过来,最后,原先的数组再被回收。可见vector容量的扩大是一个颇费时间的事。 
通常,默认的10个元素大小是不够的。你最好能准确的估计你所需要的最佳大小。 

例子: 
  1. import java.util.vector;  
  2. public class dic {  
  3.     public void addobjects (object[] o) {  
  4.         // if length > 10, vector needs to expand  
  5.         for (int i = 0; i< o.length;i++) {      
  6.             v.add(o);   // capacity before it can add more elements.  
  7.         }  
  8.     }  
  9.     public vector v = new vector();  // no initialcapacity.  
  10. }  
<span style="font-family:Arial;font-size:12px;">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.
}
</span>

更正: 
自己设定初始大小。 
  1. public vector v = new vector(20);    
  2. public hashtable hash = new hashtable(10);  
<span style="font-family:Arial;font-size:12px;">    public vector v = new vector(20);  
    public hashtable hash = new hashtable(10);</span>




三、在finally块中关闭stream 

程序中使用到的资源应当被释放,以避免资源泄漏。这最好在finally块中去做。不管程序执行的结果如何,finally块总是会执行的,以确保资源的正确关闭。 
         
例子: 
  1. import java.io.*;  
  2. public class cs {  
  3.     public static void main (string args[]) {  
  4.         cs cs = new cs ();  
  5.         cs.method ();  
  6.     }  
  7.     public void method () {  
  8.         try {  
  9.             fileinputstream fis = new fileinputstream ("cs.java");  
  10.             int count = 0;  
  11.             while (fis.read () != -1)  
  12.                 count++;  
  13.             system.out.println (count);  
  14.             fis.close ();  
  15.         } catch (filenotfoundexception e1) {  
  16.         } catch (ioexception e2) {  
  17.         }  
  18.     }  
  19. }  
<span style="font-family:Arial;font-size:12px;">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) {
        }
    }
}</span>

         
更正: 
在最后一个catch后添加一个finally块 

 
四、使用'system.arraycopy ()'代替通过来循环复制数组 

'system.arraycopy ()' 要比通过循环来复制数组快的多。 
         
例子: 
  1. public class irb  
  2. {  
  3.     void method () {  
  4.         int[] array1 = new int [100];  
  5.         for (int i = 0; i < array1.length; i++) {  
  6.             array1 [i] = i;  
  7.         }  
  8.         int[] array2 = new int [100];  
  9.         for (int i = 0; i < array2.length; i++) {  
  10.             array2 [i] = array1 [i];                 // violation  
  11.         }  
  12.     }  
  13. }  
<span style="font-family:Arial;font-size:12px;">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
        }
    }
}</span>

         
更正: 
  1. public class irb  
  2. {  
  3.     void method () {  
  4.         int[] array1 = new int [100];  
  5.         for (int i = 0; i < array1.length; i++) {  
  6.             array1 [i] = i;  
  7.         }  
  8.         int[] array2 = new int [100];  
  9.         system.arraycopy(array1, 0, array2, 0100);  
  10.     }  
  11. }  
<span style="font-family:Arial;font-size:12px;">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);
    }
}</span>

          

五、让访问实例内变量的getter/setter方法变成”final” 

简单的getter/setter方法应该被置成final,这会告诉编译器,这个方法不会被重载,所以,可以变成”inlined” 

例子: 
  1. class maf {  
  2.     public void setsize (int size) {  
  3.          _size = size;  
  4.     }  
  5.     private int _size;  
  6. }  
<span style="font-family:Arial;font-size:12px;">class maf {
    public void setsize (int size) {
         _size = size;
    }
    private int _size;
}</span>


更正: 
  1. class daf_fixed {  
  2.     final public void setsize (int size) {  
  3.          _size = size;  
  4.     }  
  5.     private int _size;  
  6. }  
<span style="font-family:Arial;font-size:12px;">class daf_fixed {
    final public void setsize (int size) {
         _size = size;
    }
    private int _size;
}</span>




 

 

 

 

六、避免不需要的instanceof操作 

如果左边的对象的静态类型等于右边的,instanceof表达式返回永远为true。 
         
例子:         

  1. public class uiso {  
  2.     public uiso () {}  
  3. }  
  4. class dog extends uiso {  
  5.     void method (dog dog, uiso u) {  
  6.         dog d = dog;  
  7.         if (d instanceof uiso) // always true.  
  8.             system.out.println("dog is a uiso");  
  9.         uiso uiso = u;  
  10.         if (uiso instanceof object) // always true.  
  11.             system.out.println("uiso is an object");  
  12.     }  
  13. }  
<span style="font-family:Arial;font-size:12px;">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");
    }
}</span>

         
更正:         
删掉不需要的instanceof操作。 
         
  1. class dog extends uiso {  
  2.     void method () {  
  3.         dog d;  
  4.         system.out.println ("dog is an uiso");  
  5.         system.out.println ("uiso is an uiso");  
  6.     }  
  7. }  
<span style="font-family:Arial;font-size:12px;">class dog extends uiso {
    void method () {
        dog d;
        system.out.println ("dog is an uiso");
        system.out.println ("uiso is an uiso");
    }
}</span>



 

 

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

所有的类都是直接或者间接继承自object。同样,所有的子类也都隐含的“等于”其父类。那么,由子类造型至父类的操作就是不必要的了。 
例子: 

  1. class unc {  
  2.     string _id = "unc";  
  3. }  
  4. class dog extends unc {  
  5.     void method () {  
  6.         dog dog = new dog ();  
  7.         unc animal = (unc)dog;  // not necessary.  
  8.         object o = (object)dog;         // not necessary.  
  9.     }  
  10. }  
<span style="font-family:Arial;font-size:12px;">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.
    }
}</span>

         
更正:         
  1. class dog extends unc {  
  2.     void method () {  
  3.         dog dog = new dog();  
  4.         unc animal = dog;  
  5.         object o = dog;  
  6.     }  
  7. }  
  8.      
<span style="font-family:Arial;font-size:12px;">class dog extends unc {
    void method () {
        dog dog = new dog();
        unc animal = dog;
        object o = dog;
    }
}
   </span>

 

      

八、如果只是查找单个字符的话,用charat()代替startswith() 

用一个字符作为参数调用startswith()也会工作的很好,但从性能角度上来看,调用用string api无疑是错误的! 
         
例子: 

  1. public class pcts {  
  2.     private void method(string s) {  
  3.         if (s.startswith("a")) { // violation  
  4.             // ...  
  5.         }  
  6.     }  
  7. }  
<span style="font-family:Arial;font-size:12px;">public class pcts {
    private void method(string s) {
        if (s.startswith("a")) { // violation
            // ...
        }
    }
}</span>

         
更正         
将'startswith()' 替换成'charat()'. 
  1. public class pcts {  
  2.     private void method(string s) {  
  3.         if ('a' == s.charat(0)) {  
  4.             // ...  
  5.         }  
  6.     }  
  7. }  
<span style="font-family:Arial;font-size:12px;">public class pcts {
    private void method(string s) {
        if ('a' == s.charat(0)) {
            // ...
        }
    }
}</span>


 

          
 

九、使用移位操作来代替'a / b'操作 

"/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。 

例子: 

  1. public class sdiv {  
  2.     public static final int num = 16;  
  3.     public void calculate(int a) {  
  4.         int div = a / 4;            // should be replaced with "a >> 2".  
  5.         int div2 = a / 8;         // should be replaced with "a >> 3".  
  6.         int temp = a / 3;  
  7.     }  
  8. }  
<span style="font-family:Arial;font-size:12px;">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;
    }
}</span>


更正: 
  1. public class sdiv {  
  2.     public static final int num = 16;  
  3.     public void calculate(int a) {  
  4.         int div = a >> 2;    
  5.         int div2 = a >> 3;  
  6.         int temp = a / 3;       // 不能转换成位移操作  
  7.     }  
  8. }  
<span style="font-family:Arial;font-size:12px;">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;       // 不能转换成位移操作
    }
}</span>


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

同上。 
[i]但我个人认为,除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。 

例子: 
  1. public class smul {  
  2.     public void calculate(int a) {  
  3.         int mul = a * 4;            // should be replaced with "a << 2".  
  4.         int mul2 = 8 * a;         // should be replaced with "a << 3".  
  5.         int temp = a * 3;  
  6.     }  
  7. }  
<span style="font-family:Arial;font-size:12px;">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;
    }
}</span>


更正: 
  1. package opt;  
  2. public class smul {  
  3.     public void calculate(int a) {  
  4.         int mul = a << 2;    
  5.         int mul2 = a << 3;  
  6.         int temp = a * 3;       // 不能转换  
  7.     }  
  8. }  
<span style="font-family:Arial;font-size:12px;">package opt;
public class smul {
    public void calculate(int a) {
        int mul = a << 2;  
        int mul2 = a << 3;
        int temp = a * 3;       // 不能转换
    }
}</span>



 

 

 

 

十一、在字符串相加的时候,使用 ' ' 代替 " ",如果该字符串只有一个字符的话 


例子: 

  1. public class str {  
  2.     public void method(string s) {  
  3.         string string = s + "d"  // violation.  
  4.         string = "abc" + "d"      // violation.  
  5.     }  
  6. }  
<span style="font-family:Arial;font-size:12px;">public class str {
    public void method(string s) {
        string string = s + "d"  // violation.
        string = "abc" + "d"      // violation.
    }
}
</span>

更正: 
将一个字符的字符串替换成' ' 
  1. public class str {  
  2.     public void method(string s) {  
  3.         string string = s + 'd'  
  4.         string = "abc" + 'd'     
  5.     }  
  6. }  
<span style="font-family:Arial;font-size:12px;">public class str {
    public void method(string s) {
        string string = s + 'd'
        string = "abc" + 'd'   
    }
}
</span>


 

 

 

 

十二、不要在循环中调用synchronized(同步)方法 

方法的同步需要消耗相当大的资料,在一个循环中调用它绝对不是一个好主意。 

例子: 

  1. import java.util.vector;  
  2. public class syn {  
  3.     public synchronized void method (object o) {  
  4.     }  
  5.     private void test () {  
  6.         for (int i = 0; i < vector.size(); i++) {  
  7.             method (vector.elementat(i));    // violation  
  8.         }  
  9.     }  
  10.     private vector vector = new vector (55);  
  11. }  
<span style="font-family:Arial;font-size:12px;">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);
}</span>


更正: 
不要在循环体中调用同步方法,如果必须同步的话,推荐以下方式: 
  1. import java.util.vector;  
  2. public class syn {  
  3.     public void method (object o) {  
  4.     }  
  5. private void test () {  
  6.     synchronized{//在一个同步块中执行非同步方法  
  7.             for (int i = 0; i < vector.size(); i++) {  
  8.                 method (vector.elementat(i));     
  9.             }  
  10.         }  
  11.     }  
  12.     private vector vector = new vector (55);  
  13. }  
<span style="font-family:Arial;font-size:12px;">import java.util.vector;
public class syn {
    public void method (object o) {
    }
private void test () {
    synchronized{//在一个同步块中执行非同步方法
            for (int i = 0; i < vector.size(); i++) {
                method (vector.elementat(i));   
            }
        }
    }
    private vector vector = new vector (5, 5);
}</span>



 

 

 

 

十三、将try/catch块移出循环 

把try/catch块放入循环体内,会极大的影响性能,如果编译jit被关闭或者你所使用的是一个不带jit的jvm,性能会将下降21%之多! 
         
例子:         

  1. import java.io.fileinputstream;  
  2. public class try {  
  3.     void method (fileinputstream fis) {  
  4.         for (int i = 0; i < size; i++) {  
  5.             try {                                      // violation  
  6.                 _sum += fis.read();  
  7.             } catch (exception e) {}  
  8.         }  
  9.     }  
  10.     private int _sum;  
  11. }  
<span style="font-family:Arial;font-size:12px;">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;
}</span>

         
更正:         
将try/catch块移出循环         
  
  1. void method (fileinputstream fis) {  
  2.        try {  
  3.            for (int i = 0; i < size; i++) {  
  4.                _sum += fis.read();  
  5.            }  
  6.        } catch (exception e) {}  
  7.    }  
<span style="font-family:Arial;font-size:12px;"> void method (fileinputstream fis) {
        try {
            for (int i = 0; i < size; i++) {
                _sum += fis.read();
            }
        } catch (exception e) {}
    }</span>


 

          
 

十四、对于boolean值,避免不必要的等式判断 

将一个boolean值与一个true比较是一个恒等操作(直接返回该boolean变量的值). 移走对于boolean的不必要操作至少会带来2个好处: 
1)代码执行的更快 (生成的字节码少了5个字节); 
2)代码也会更加干净 。 

例子: 

  1. public class ueq  
  2. {  
  3.     boolean method (string string) {  
  4.         return string.endswith ("a") == true;   // violation  
  5.     }  
  6. }  
<span style="font-family:Arial;font-size:12px;">public class ueq
{
    boolean method (string string) {
        return string.endswith ("a") == true;   // violation
    }
}</span>


更正: 
  1. class ueq_fixed  
  2. {  
  3.     boolean method (string string) {  
  4.         return string.endswith ("a");  
  5.     }  
  6. }  
<span style="font-family:Arial;font-size:12px;">class ueq_fixed
{
    boolean method (string string) {
        return string.endswith ("a");
    }
}</span>



 

 

 

 

十五、对于常量字符串,用'string' 代替 'stringbuffer' 

常量字符串并不需要动态改变长度。 
例子: 

  1. public class usc {  
  2.     string method () {  
  3.         stringbuffer s = new stringbuffer ("hello");  
  4.         string t = s + "world!";  
  5.         return t;  
  6.     }  
  7. }  
<span style="font-family:Arial;font-size:12px;">public class usc {
    string method () {
        stringbuffer s = new stringbuffer ("hello");
        string t = s + "world!";
        return t;
    }
}</span>



 

更正: 
把stringbuffer换成string,如果确定这个string不会再变的话,这将会减少运行开销提高性能。 

十六、用'stringtokenizer' 代替 'indexof()' 和'substring()' 

字符串的分析在很多应用中都是常见的。使用indexof()和substring()来分析字符串容易导致 stringindexoutofboundsexception。而使用stringtokenizer类来分析字符串则会容易一些,效率也会高一些。 

例子: 

  1. public class ust {  
  2.     void parsestring(string string) {  
  3.         int index = 0;  
  4.         while ((index = string.indexof(".", index)) != -1) {  
  5.             system.out.println (string.substring(index, string.length()));  
  6.         }  
  7.     }  
  8. }  
<span style="font-family:Arial;font-size:12px;">public class ust {
    void parsestring(string string) {
        int index = 0;
        while ((index = string.indexof(".", index)) != -1) {
            system.out.println (string.substring(index, string.length()));
        }
    }
}
</span>




 

 

 

 

十七、使用条件操作符替代"if (cond) return; else return;" 结构 

条件操作符更加的简捷 
例子: 

  1. public class if {  
  2.     public int method(boolean isdone) {  
  3.         if (isdone) {  
  4.             return 0;  
  5.         } else {  
  6.             return 10;  
  7.         }  
  8.     }  
  9. }  
<span style="font-family:Arial;font-size:12px;">public class if {
    public int method(boolean isdone) {
        if (isdone) {
            return 0;
        } else {
            return 10;
        }
    }
}</span>


更正: 
  1. public class if {  
  2.     public int method(boolean isdone) {  
  3.         return (isdone ? 0 : 10);  
  4.     }  
  5. }  
<span style="font-family:Arial;font-size:12px;">public class if {
    public int method(boolean isdone) {
        return (isdone ? 0 : 10);
    }
}</span>


 

 

 

 

十八、使用条件操作符代替"if (cond) a = b; else a = c;" 结构 

例子: 

  1. public class ifas {  
  2.     void method(boolean istrue) {  
  3.         if (istrue) {  
  4.             _value = 0;  
  5.         } else {  
  6.             _value = 1;  
  7.         }  
  8.     }  
  9.     private int _value = 0;  
  10. }  
<span style="font-family:Arial;font-size:12px;">public class ifas {
    void method(boolean istrue) {
        if (istrue) {
            _value = 0;
        } else {
            _value = 1;
        }
    }
    private int _value = 0;
}</span>


更正: 
  1. public class ifas {  
  2.     void method(boolean istrue) {  
  3.         _value = (istrue ? 0 : 1);       // compact expression.  
  4.     }  
  5.     private int _value = 0;  
  6. }  
<span style="font-family:Arial;font-size:12px;">public class ifas {
    void method(boolean istrue) {
        _value = (istrue ? 0 : 1);       // compact expression.
    }
    private int _value = 0;
}
</span>


 

 

 

 

十九、不要在循环体中实例化变量 

在循环体中实例化临时变量将会增加内存消耗 

例子:         

  1. import java.util.vector;  
  2. public class loop {  
  3.     void method (vector v) {  
  4.         for (int i=0;i < v.size();i++) {  
  5.             object o = new object();  
  6.             o = v.elementat(i);  
  7.         }  
  8.     }  
  9. }  
<span style="font-family:Arial;font-size:12px;">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);
        }
    }
}</span>

         
更正:         
在循环体外定义变量,并反复使用         
  1. import java.util.vector;  
  2. public class loop {  
  3.     void method (vector v) {  
  4.         object o;  
  5.         for (int i=0;i<v.size();i++) {  
  6.             o = v.elementat(i);  
  7.         }  
  8.     }  
  9. }  
<span style="font-family:Arial;font-size:12px;">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);
        }
    }
}</span>



 

 

 

 

二十、确定 stringbuffer的容量 

stringbuffer的构造器会创建一个默认大小(通常是16)的字符数组。在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再丢弃旧的数组。在大多数情况下,你可以在创建stringbuffer的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。 

例子:         

  1. public class rsbc {  
  2.     void method () {  
  3.         stringbuffer buffer = new stringbuffer(); // violation  
  4.         buffer.append ("hello");  
  5.     }  
  6. }  
<span style="font-family:Arial;font-size:12px;">public class rsbc {
    void method () {
        stringbuffer buffer = new stringbuffer(); // violation
        buffer.append ("hello");
    }
}</span>

         
更正:         
为stringbuffer提供寝大小。         
  1. public class rsbc {  
  2.     void method () {  
  3.         stringbuffer buffer = new stringbuffer(max);  
  4.         buffer.append ("hello");  
  5.     }  
  6.     private final int max = 100;  
  7. }  
<span style="font-family:Arial;font-size:12px;">public class rsbc {
    void method () {
        stringbuffer buffer = new stringbuffer(max);
        buffer.append ("hello");
    }
    private final int max = 100;
}</span>

          
 

二十一、尽可能的使用栈变量 

如果一个变量需要经常访问,那么你就需要考虑这个变量的作用域了。static? local?还是实例变量?访问静态变量和实例变量将会比访问局部变量多耗费2-3个时钟周期。 
         
例子: 
  1. public class usv {  
  2.     void getsum (int[] values) {  
  3.         for (int i=0; i < value.length; i++) {  
  4.             _sum += value[i];           // violation.  
  5.         }  
  6.     }  
  7.     void getsum2 (int[] values) {  
  8.         for (int i=0; i < value.length; i++) {  
  9.             _staticsum += value[i];  
  10.         }  
  11.     }  
  12.     private int _sum;  
  13.     private static int _staticsum;  
  14. }       
<span style="font-family:Arial;font-size:12px;">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;
}     </span>

         
更正:         
如果可能,请使用局部变量作为你经常访问的变量。 
你可以按下面的方法来修改getsum()方法:         
  1. void getsum (int[] values) {  
  2.     int sum = _sum;  // temporary local variable.  
  3.     for (int i=0; i < value.length; i++) {  
  4.         sum += value[i];  
  5.     }  
  6.     _sum = sum;  
  7. }  
<span style="font-family:Arial;font-size:12px;">void getsum (int[] values) {
    int sum = _sum;  // temporary local variable.
    for (int i=0; i < value.length; i++) {
        sum += value[i];
    }
    _sum = sum;
}</span>


 

          
 

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

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

例子: 

  1. public class dun {  
  2.     boolean method (boolean a, boolean b) {  
  3.         if (!a)  
  4.             return !a;  
  5.         else  
  6.             return !b;  
  7.     }  
  8. }  
<span style="font-family:Arial;font-size:12px;">public class dun {
    boolean method (boolean a, boolean b) {
        if (!a)
            return !a;
        else
            return !b;
    }
}</span>



 

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

二十三、与一个接口 进行instanceof操作 

基于接口的设计通常是件好事,因为它允许有不同的实现,而又保持灵活。只要可能,对一个对象进行instanceof操作,以判断它是否某一接口要比是否某一个类要快。 

例子: 

  1. public class insof {  
  2.     private void method (object o) {  
  3.         if (o instanceof interfacebase) { }  // better  
  4.         if (o instanceof classbase) { }   // worse.  
  5.     }  
  6. }  
  7.   
  8. class classbase {}  
  9. interface interfacebase {}  

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值