zoukankan      html  css  js  c++  java
  • JAVA代码优化

    写Java也有n年了,现在还是有不少的坏的代码习惯,也通过学习别人的代码学到了不少好的习惯。这篇文章主要是整理的资料。

    留给自己做个警戒,提示以后写代码的时候注意!在文章的后面,会提供整理的原材料下载。

    一、类和对象使用技巧

    1、尽量少用new生成新对象

            用new创建类的实例时,构造雨数链中所有构造函数都会被自动调用,操作速度较慢。在某些时候可复用现有对象。

    比如在进行大量St rillg操作时,可用StringBuffer娄代替String类,以避免生成大量的对象。用 new关键词创建类的实例时,

    构造函数链中的所有构造函数都会被自动调用。但如果一个对象实现了 Cloneable 接口,我们可以调用她的 clone() 方法。

    clone()方法不会调用任何类构造函数。  

            下面是 Factory 模式的一个典型实现。    

     

    1. public static Credit getNewCredit()   
    public static Credit getNewCredit() 
    1. {   
    { 
    1. return new Credit();   
        return new Credit(); 
    1. }   
    } 
     
    改进后的代码使用 clone() 方法,  
     
    1. private static Credit BaseCredit = new Credit();   
    2. public static Credit getNewCredit()   
    3. {   
    4.     return (Credit)BaseCredit.clone();   
    5. }   
    private static Credit BaseCredit = new Credit(); 
    public static Credit getNewCredit() 
    { 
        return (Credit)BaseCredit.clone(); 
    } 

    2、使用clone()方法生成新对象

            如果一个对象实现Cloneable接口,就可以调用它的clone()方法。clone()方法不会泪用任何类构造函数,
    比使用new方法创建实例速度要快。

    3、尽量使用局部变量(栈变量)

            调用方法时传递的参数及调用中创建的临时变量保存在栈(Stack)中,速度较快。其他变量,如静态变量、实例变量都在堆(HeaP)中创建,速度较慢。

    访问静态变量和实例变量将会比访问局部变量多耗费 2-3 个时钟周期。如果一个变量需要经常访问,那么你就需要考虑这个变量的作用域了。

    static? local?还是实例变量?  

            调用方法时传递的参数以及在调用中创建的临时变量都保存在栈(Stack)中,速度较快。其他变量,如静态变量,实例变量等,都在堆(Heap)中创建,

    速度较慢。

                       例子:    

    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. }        
    15.    
    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; 
    }      
     
                     更正:如果可能,请使用局部变量作为你经常访问的变量。  你可以按下面的方法来修改 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;   
    void getsum (int[] values) { 
        int sum = _sum;  // temporary local variable. 
        for (int i=0; i < value.length; i++) { 
            sum += value[i]; 
        } 
        _sum = sum; 

    4、减少方法调用

            面向对象设计的一个基本准则是通过方法间接访问对象的属性,但方法调用会占用·些开销访问。
    可以避免在同一个类中通过训州函数或方法(get或set)来设置或调用该对象的灾例变量,这比直接访问变量要慢。
    为了减少方法调用,可以将方法中的代码复制到调用方法的地方,比如大量的循环中,这样可以节省方法调用的开销。
    但带来性能提升的同时会牺牲代码的可读性,可根据实际需要平衡两者关系。

    5、使用final类和final、static、private方法

            带有final修饰符的类是不可派生的。如果指定一个类为finaI,则该类所有的方法都是final。JAVA编障器会寻找机会内联(inIine)所有的final方法。

    此举能够提升程序性能。使用final、static、private的方法是不能被覆盖的,JAVA不需要在稃序运行的时候动态关联实现方法,从而节省了运行时间。

            带有 final 修饰符的类是不可派生的。在 JAVA核心 API中,有许多应用 final 的例子,例如 java.lang.String。

    为 String 类指定 final 防止了使用者覆盖 length()方法。另外,如果一个类是 final 的,则该类所有方法都是 final 的。

    java 编译器会寻找机会内联(inline)所有的final 方法(这和具体的编译器实现有关)。此举能够使性能平均提高 50%。 

    6、让访问实例内变量的 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. }   
    class maf { 
        public void setsize (int size) { 
             _size = size; 
        } 
        private int _size; 
    } 
    更正:   
    1. class daf_fixed {   
    2.     final public void setsize (int size) {   
    3.          _size = size;   
    4.     }   
    5.     private int _size;   
    6. }   
    class daf_fixed { 
        final public void setsize (int size) { 
             _size = size; 
        } 
        private int _size; 
    } 

    7、避免不需要的 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. }   
    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 操作。               

    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. }   
    class dog extends uiso { 
        void method () { 
            dog d; 
            system.out.println ("dog is an uiso"); 
            system.out.println ("uiso is an uiso"); 
        } 
    } 

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

     
            所有的类都是直接或者间接继承自 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. }   
    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. 
        } 
    } 
                更正:            
    1. class dog extends unc {   
    2.     void method () {   
    3.         dog dog = new dog();   
    4.         unc animal = dog;   
    5.         object o = dog;   
    6.     }   
    7. }   
    class dog extends unc { 
        void method () { 
            dog dog = new dog(); 
            unc animal = dog; 
            object o = dog; 
        } 
    } 

    9.尽量重用对象。  

            特别是 String 对象的使用中,出现字符串连接情况时应使用 StringBuffer 代替,由于系统不仅要花时间生成对象,
    以后可能还需要花时间对这些对象进行垃圾回收和处理。因此生成过多的对象将会给程序的性能带来很大的影响。  
     

    10、不要重复初始化变量。  

            默认情况下,调用类的构造函数时,java 会把变量初始化成确定的值,所有的对象被设置成null,

    整数变量设置成 0,float 和 double 变量设置成 0.0,逻辑值设置成 false。当一个类从另一个类派生时,

    这一点尤其应该注意,因为用 new 关键字创建一个对象时,构造函数链中的所有构造函数都会被自动调用。  

    这里有个注意,给成员变量设置初始值但需要调用其他方法的时候,最好放在一个方法比如initXXX()中,

    因为直接调用某方法赋值可能会因为类尚未初始化而抛空指针异常,public int state = this.getState();  

    11、不要过分创建对象

            过分的创建对象会消耗系统的大量内存,严重时,会导致内存泄漏,因此,保证过期的对象的及时回收具有重要意义。  

    JVM 的 GC并非十分智能,因此建议在对象使用完毕后,手动设置成 null。

    二、Java I/O技巧

            I/O性能常常是应用程序性能瓶颈,优化I/O性能就显得极为系要。在进行I/0操作时,匿遵循以下原则:尽可能少的访问磁盘;
    尽可能少的I方问底层的操作系统;尽可能少的方法调用;尽可能少处理个别的处理字节和字符。基于以上原则,可以通过以下技巧提高I/O速度:

    1、使州缓冲提高I/O性能。

            常用的实现方法有以下2种:使用用于字符的BufferedReader和用于宁节的BufferedlnputStream类,或者使用块读取方法次读取一大块数据。

    2、lnputStream比Reader高效,OutputStream比Writer高效。

            当使用Unicode字符串时,Write类的开销比较大。因为它要实Uoicode到字节(byte)的转换。

    因此,如果可能的话,在使用 Write类之前就实现转换或用OutputStream类代替Writer娄来使用。

    3、在适当的时候用byte替代char。

            1个char用2个字节保存字符,而byte只需要1个,因此用byte保存字符消耗的内存和需要执行的机器指令更少。

    更重要的是,用byte避免了进行Unicode转换。因此,如果町能的话,应尽量使用byte替代char。

    4、有缓冲的块操作10要比缓冲的流字符IO快。

            对于字符IO,虽然缓冲流避免了每次读取字符时的系统调用开销,但仍需要一次或多次方法调用。

    带缓冲的块10比缓冲流IO快2到4倍,比无缓冲的IO快4到40倍。

    5、序列化时,使用原子类型。

            当序列化一个类或对象时,对干那些原子类型(atomic)或可以重建的元素,要标识为transient类型,

    这样就不用每一次都进行序列化。如果这砦序列化的对象要在网络上传输,这一小小的改变对性能会有很大的提高。

    6、在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. }   
    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) { 
            } 
        } 
    } 
             
    更正:  
    在最后一个 catch 后添加一个 finally 块  

    7、SQL语句

    在 java+Oracle 的应用系统开发中,java 中内嵌的 SQL 语言应尽量使用大写形式,以减少Oracle 解析器的解析负担。

    8、尽早释放资源

            java 编程过程中,进行数据库连接,I/O 流操作,在使用完毕后,及时关闭以释放资源。因为对这些大对象的操作会造成系统大的开销。 

    三、异常(Exceptions)使用技巧

            JAVA语言中提供了try/catch来开发方便用户捕捉异常,进行异常的处理。但是如果使用不当,也会给JAvA程序的性能带来影响。
    因此,要注意以下儿点。慎用异常,异常对性能不利。抛出异常首先要创建一个新的对象。
    Throwable接口的构造函数调用名为fillInStackTrace()的本地(Native)方法filllnStackTrace()方法检查堆栈,收集调用跟踪信息。
    只要有异常被抛出,VM就必须调整调用堆栈。

    1、避免使用异常来控制程序流程

            如果可以用if、while等逻辑语句来处理,那么就尽可能的不用try/catch语句。抛出异常首先要创建一个新的对象。
    Throwable 接口的构造函数调用名为 fillInStackTrace()的本地方法,fillInStackTrace()方法检查栈,收集调用跟踪信息。
    只要有异常被抛出,VM 就必须调整调用栈,因为在处理过程中创建了一个新的对象。  异常只能用于错误处理,不应该用来控制程序流程。  

    2、尽可能重用异常

            在必须要进行异常的处理时,要尽可能的重用已经存在的异常对象。因为在异常的处理中,生成个异常对象要消耗掉大部分的时间。

    3、将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. }   
    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块移出循环          
        
    1. void method (fileinputstream fis) {   
    2.        try {   
    3.            for (int i = 0; i < size; i++) {                 _sum += fis.read();   
    4.            }   
    5.        } catch (exception e) {}   
    6.    }   
     void method (fileinputstream fis) { 
            try { 
                for (int i = 0; i < size; i++) {                 _sum += fis.read(); 
                } 
            } catch (exception e) {} 
        } 
     
            

    四、线程使用技巧

    1、在使用大量线程(Threading)的场合使用线程池管理

            生成和启动新线程是个相对较慢的过程,生成人量新线程会严重影响应J_}j程序性能。

    通过使用线程池,由线程池管理器(thread pool manager)来生成新线程或分配现有线程,柏省生成线程的叫间。

    2、防止过多的同步

            不必要的同步常常会造成程序性能的下降,调用同步方法比调用非同步方法要花费更多的时间。如果程序是单线程,则没有必要使用同步。

    3、同步方法而不要同步整个代码段

    对某个方法或函数进行同步比对整个代码段进行同步的性能要好。

    4、在追求速度的场合,用ArrayList和HashMap代替Vector和Hashtable

            Vector和Hashtable实现了同步以提高线程安全性,但速度较没有实现同步的ArrayList和Ha shMap要慢,可以根据需要选择使用的类。

    5、使用notify()而不是notifyAll()

            使用哪个方法要取决于程序的没计,但应尽可能使用notify(),因为notify()只唤醒等待指定对象的线程,比唤醒所有等待线稃的notifyAll0速度更快。

    6、不要在循环中调用 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 (5, 5);   
    11. }   
    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); 
    } 
    更正:不要在循环体中调用同步方法,如果必须同步的话,推荐以下方式:  
     
    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 (5, 5);   
    13. }   
    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); 
    } 

    7、单线程应尽量使用 HashMap, ArrayList。

    除非必要,否则不推荐使用 HashTable,Vector,她们使用了同步机制,而降低了性能。  

    五、其它常用技巧

    1、使用移位操作替代乘除法操作可以极大地提高性能

           "/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。     例子:
     
    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.     int mul = a * 4;            // should be replaced with "a << 2".   
    8.     int mul2 = 8 * a;         // should be replaced with "a << 3".   
    9.     int temp2 = a * 3;   
    10.     }   
    11. }   
    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; 
    	int mul = a * 4;            // should be replaced with "a << 2". 
    	int mul2 = 8 * a;         // should be replaced with "a << 3". 
    	int temp2 = a * 3; 
        } 
    } 
    更正:    
    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.     int mul = a << 2;     
    8.     int mul2 = a << 3;   
    9.     int temp = a * 3;       // 不能转换   
    10.     }   
    11. }   
    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;       // 不能转换成位移操作 
     	int mul = a << 2;   
     	int mul2 = a << 3; 
     	int temp = a * 3;       // 不能转换 
        } 
    } 
            PS:除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。
    否则提高性能所带来的程序晚读性的降低将是不合算的。
     

    2、对Vector中最后位置的添加、删除操作要远远快于埘第一个元素的添加、删除操作

    3、当复制数组时,使用System.arraycop()方法

            例子:    
    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. }   
    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 
            } 
        } 
    } 
                 更正:  
     
    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, 0, 100);   
    10.     }   
    11. }   
    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); 
        } 
    } 
     

    4、使用复合赋值运算符

            a=a+b和a+b住编译时会产生不同JAVA字奇码,后者回快于前者。冈此,使用+=、-=、+=、/=等复台赋值运算符会使运算速度稍有提升。

    5、用int而不用其它基本类型

    对int类犁的操作通常比其它基本类型要快,因此尽量使用int类型。

    6、在进行数据库连接和网络连接时使用连接池

    这类连接往往会耗费大量时间,应尽量避免。可以使用连接池技术,复用现有连接。

    7、用压缩加快网络传输速度一种常用方法是把相关文件打包到一个jar文件中。

    用一个Jar文件发送多个文件还叫以避免每个文件打开和关闭网络连接所造成的开销。

    8、在数据库应用程序中使用批处理功能

            可以利用Statement类的addBatch()氟l exexuteBatch法成批地提交sql语句,以节省网络传输开销。

    在执行大量相似语句时,可以使用PreParedState—类,它可以一次性编译语句并多次执行,用参数最后执行的sql语句。

    9、消除循环体中不必要的代码

    这似乎是每个程序员都知道的基本原则,没有必出,但很多人往往忽略一些细节。如下列代码:
    1. Vector aVector= ...;  
    2. for(int i=0;i<aVector size();i++)(  
    3. System out printlll(aVector elementAt(i)toStringO);  
    4. }  
    Vector aVector= ...;
    for(int i=0;i<aVector size();i++)(
    System out printlll(aVector elementAt(i)toStringO);
    }
    这段代码中没循环一次就要调用aVector.size()方法,aVector的长度不变的话,可以改为一下代码:
    1. Vector aVector= ...:  
    2. int length=aVector size();  
    3. for(int i=0;i<length;i++)f  
    4. System out println(aVector elememAt(i)toStringO);  
    5. )  
    Vector aVector= ...:
    int length=aVector size();
    for(int i=0;i<length;i++)f
    System out println(aVector elememAt(i)toStringO);
    )
    这样消除了每次调用aVector.size()方法的开销。

    10、为'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. }   
    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. 
    } 
    1. <span style="white-space: pre;">    </span><span style="font-size: 14px;">更正:  自己设定初始大小。 </span>   
    	更正:  自己设定初始大小。  
    1. public vector v = new vector(20);     
    2.     public hashtable hash = new hashtable(10);   
    public vector v = new vector(20);   
        public hashtable hash = new hashtable(10); 

    11、如果只是查找单个字符的话,用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. }      
    public class pcts { 
        private void method(string s) { 
            if (s.startswith("a")) { // violation 
                // ... 
            } 
        } 
    }    
    更正 :将'startswith()' 替换成'charat()'.  
     
    1. public class pcts {   
    2.     private void method(string s) {   
    3.         if ('a' == s.charat(0)) {   
    4.             // ...   
    5.         }   
    6.     }   
    7. }   
    public class pcts { 
        private void method(string s) { 
            if ('a' == s.charat(0)) { 
                // ... 
            } 
        } 
    } 

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

              例子:    
    1. public class str {   
    2.     public void method(string s) {   
    3.         string string = s + "d"  // violation.   
    4.         string = "abc" + "d"      // violation.   
    5.     }   
    6. }   
    public class str { 
        public void method(string s) { 
            string string = s + "d"  // violation. 
            string = "abc" + "d"      // violation. 
        } 
    } 
     
    更正:  将一个字符的字符串替换成' '  
     
    1. public class str {   
    2.     public void method(string s) {   
    3.         string string = s + 'd'   
    4.         string = "abc" + 'd'      
    5.     }   
    6. }   
    public class str { 
        public void method(string s) { 
            string string = s + 'd' 
            string = "abc" + 'd'    
        } 
    } 

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

     
            将一个 boolean 值与一个 true 比较是一个恒等操作(直接返回该 boolean 变量的值). 移走对于boolean 的不必要操作至少会带来 2 个好处:  

    1)代码执行的更快 (生成的字节码少了 5 个字节);   2)代码也会更加干净 。  

     
            例子:    
    1. public class ueq {   
    2.     boolean method (string string) {   
    3.         return string.endswith ("a") == true;   // violation   
    4.     }   
    5. }   
    public class ueq { 
        boolean method (string string) { 
            return string.endswith ("a") == true;   // violation 
        } 
    } 
            更正:    
    1. class ueq_fixed  {   
    2.     boolean method (string string) {   
    3.         return string.endswith ("a");   
    4.     }   
    5. }   
    class ueq_fixed  { 
        boolean method (string string) { 
            return string.endswith ("a"); 
        } 
    } 

    14、对于常量字符串,用'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. }   
    public class usc { 
        string method () { 
            stringbuffer s = new stringbuffer ("hello"); 
            string t = s + "world!"; 
            return t; 
        } 
    } 
    更正:   把 stringbuffer 换成 string,如果确定这个 string 不会再变的话,这将会减少运行开销提高性能。
     
     

    15、用'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. }   
    public class ust { 
        void parsestring(string string) { 
            int index = 0; 
            while ((index = string.indexof(".", index)) != -1) { 
                system.out.println (string.substring(index, string.length())); 
            } 
        } 
    } 

    16、使用条件操作符替代"if (cond) else " 结构  

              条件操作符更加的简捷           例子:    
    1. public class if {   
    2.     public int method(boolean isdone) {   
    3.         if (isdone) {   
    4.             return 0;   
    5.         } else {   
    6.             return 10;   
    7.         }   
    8.   
    9.      void method2(boolean istrue) {   
    10.         if (istrue) {   
    11.             _value = 0;   
    12.         } else {   
    13.             _value = 1;   
    14. <span style="white-space: pre;">    </span>}  
    15.     }   
    16. }   
    public class if { 
        public int method(boolean isdone) { 
            if (isdone) { 
                return 0; 
            } else { 
                return 10; 
            } 
    
    	 void method2(boolean istrue) { 
            if (istrue) { 
                _value = 0; 
            } else { 
                _value = 1; 
    	}
        } 
    } 
              更正:    
    1. public class if {   
    2.     public int method(boolean isdone) {   
    3.         return (isdone ? 0 : 10);   
    4.     }   
    5.   
    6.     void method(boolean istrue) {   
    7.     <span style="white-space: pre;">    </span>_value = (istrue ? 0 : 1);       // comp  
    8. <span style="white-space: pre;">    </span>}   
    9.     private int _value = 0;   
    10.   
    11. }   
    public class if { 
        public int method(boolean isdone) { 
            return (isdone ? 0 : 10); 
        } 
    
        void method(boolean istrue) { 
        	_value = (istrue ? 0 : 1);       // comp
    	} 
        private int _value = 0; 
    
    } 

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

    在循环体中实例化临时变量将会增加内存消耗  
     
    例子:          
     
    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. }   
    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); 
            } 
        } 
    } 
     
    更正:          
    在循环体外定义变量,并反复使用          
     
    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. }    
    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); 
            } 
        } 
    }  

    18、确定 stringbuffer的容量  

             stringbuffer 的构造器会创建一个默认大小(通常是 16)的字符数组。

    在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再丢弃旧的数组。

    在大多数情况下,你可以在创建 stringbuffer 的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。   例子:

         
    1. public class rsbc {   
    2.     void method () {   
    3.         stringbuffer buffer = new stringbuffer(); // violation   
    4.         buffer.append ("hello");   
    5.     }   
    6.  }      
    public class rsbc { 
        void method () { 
            stringbuffer buffer = new stringbuffer(); // violation 
            buffer.append ("hello"); 
        } 
     }    
    更正:为 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. }   
    public class rsbc { 
        void method () { 
            stringbuffer buffer = new stringbuffer(max); 
            buffer.append ("hello"); 
        } 
        private final int max = 100; 
    } 

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

     
    取反操作符(!)降低程序的可读性,所以不要总是使用。  
     
    例子:  
     
    1. public class dun {   
    2.     boolean method (boolean a, boolean b) {   
    3.         if (!a)   
    4.             return !a;   
    5.         else   
    6.             return !b;   
    7.     }   
    8. }   
    public class dun { 
        boolean method (boolean a, boolean b) { 
            if (!a) 
                return !a; 
            else 
                return !b; 
        } 
    } 
       
    更正:如果可能不要使用取反操作符(!)  
     

    20、与一个接口 进行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 {}   
    public class insof { 
        private void method (object o) { 
            if (o instanceof interfacebase) { }  // better 
            if (o instanceof classbase) { }   // worse. 
        } 
    } 
     
    class classbase {} 
    interface interfacebase {} 

      21、采用在需要的时候才开始创建的策略。  

            例如:    
    1. String str="abc";   
    2. if(i==1){ list.add(str);}   
    String str="abc"; 
    if(i==1){ list.add(str);} 
            应修改为:    
    1. if(i==1){String str="abc"; list.add(str);}   
    if(i==1){String str="abc"; list.add(str);} 

    22、通过 StringBuffer 的构造函数来设定他的初始化容量,可以明显提升性能。  

            StringBuffer 的默认容量为 16,当 StringBuffer 的容量达到最大容量时,她会将自身容量增加到当前的 2 倍+2,也就是 2*n+2。
    无论何时,只要 StringBuffer 到达她的最大容量,她就不得不创建一个新的对象数组,然后复制旧的对象数组,这会浪费很多时间。
    所以给StringBuffer 设置一个合理的初始化容量值,是很有必要的!    
     

    23、合理使用 java.util.Vector

            Vector 与 StringBuffer 类似,每次扩展容量时,所有现有元素都要赋值到新的存储空间中。
    Vector 的默认存储能力为 10个元素,扩容加倍。  vector.add(index,obj) 这个方法可以将元素 obj 插入到index 位置,
    但 index 以及之后的元素依次都要向下移动一个位置(将其索引加 1)。 除非必要,否则对性能不利。  
    同样规则适用于 remove(int index)方法,移除此向量中指定位置的元素。将所有后续元素左移(将其索引减 1)。
    返回此向量中移除的元素。所以删除 vector 最后一个元素要比删除第1 个元素开销低很多。删除所有元素最好用 removeAllElements()方法。  
    如果要删除 vector 里的一个元素可以使用 vector.remove(obj);而不必自己检索元素位置,再删除,如 int index = indexOf(obj);vector.remove(index);  
     

    24、不要将数组声明为:public static final

     

    25、HaspMap 的遍历

     
    1. Map<String, String[]> paraMap = new HashMap<String, String[]>();   
    2. for( Entry<String, String[]> entry : paraMap.entrySet() )   
    3. {   
    4.     String appFieldDefId = entry.getKey();   
    5.     String[] values = entry.getValue();   
    6. }   
    Map<String, String[]> paraMap = new HashMap<String, String[]>(); 
    for( Entry<String, String[]> entry : paraMap.entrySet() ) 
    { 
        String appFieldDefId = entry.getKey(); 
        String[] values = entry.getValue(); 
    } 
    

    利用散列值取出相应的 Entry 做比较得到结果,取得 entry的值之后直接取 key和 value。  

     

    26、array(数组)和 ArrayList 的使用。  

    array 数组效率最高,但容量固定,无法动态改变,ArrayList 容量可以动态增长,但牺牲了效率。  

    27、StringBuffer,StringBuilder 的区别

            StringBuffer,StringBuilder 的区别在于:java.lang.StringBuffer 线程安全的可变字符序列。

    一个类似于 String 的字符串缓冲区,但不能修改。StringBuilder 与该类相比,通常应该优先使用 StringBuilder 类,

    因为她支持所有相同的操作,但由于她不执行同步,所以速度更快。为了获得更好的性能,

    在构造 StringBuffer 或 StringBuilder 时应尽量指定她的容量。当然如果不超过 16 个字符时就不用了。

     相同情况下,使用 StringBuilder 比使用 StringBuffer 仅能获得 10%~15%的性能提升,但却要冒多线程不安全的风险。

    综合考虑还是建议使用 StringBuffer。  

     

    28、 尽量使用基本数据类型代替对象。    

    29、用简单的数值计算代替复杂的函数计算,比如查表方式解决三角函数问题。    

    30、使用具体类比使用接口效率高,但结构弹性降低了,但现代 IDE 都可以解决这个问题。  

    31、考虑使用静态方法

            如果你没有必要去访问对象的外部,那么就使你的方法成为静态方法。她会被更快地调用,因为她不需要一个虚拟函数导向表。
    这同事也是一个很好的实践,因为她告诉你如何区分方法的性质,调用这个方法不会改变对象的状态。  
     

    32.应尽可能避免使用内在的GET,SET 方法 

            android 编程中,虚方法的调用会产生很多代价,比实例属性查询的代价还要多。
    我们应该在外包调用的时候才使用 get,set方法,但在内部调用的时候,应该直接调用。  

    33、避免枚举,浮点数的使用。     34、二维数组比一维数组占用更多的内存空间,大概是 10 倍计算。  

    35、SQLite

            SQLite 数据库读取整张表的全部数据很快,但有条件的查询就要耗时 30-50MS,大家做这方面的时候要注意,尽量少用,尤其是嵌套查找!

    36、奇偶判断  

     
    不要使用 i % 2 == 1 来判断是否是奇数,因为 i为负奇数时不成立,请使用 i % 2 != 0 来判断是否是奇数,或使用  高效式 (i & 1) != 0 来判断。 
  • 相关阅读:
    Postfix邮件服务器搭建及配置
    利用linux漏洞进行提权
    NFS部署和优化
    LAMP环境搭建
    Apache2.4.6服务器安装及配置
    linux笔记_防止ddos攻击
    CentOS6.5恢复误删除的文件
    linux计划任务
    linux软连接和硬链接
    linux用户和用户组的基本操作
  • 原文地址:https://www.cnblogs.com/fender/p/5088625.html
Copyright © 2011-2022 走看看