Java性能调优

一、类和对象使用技巧

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

用new创建类的实例时,构造雨数链中所有构造函数都会被自动调用,操作速度较慢。在某些时候可复用现有对象。比如在进行大量String操作时,可用StringBuffer娄代替String类,以避免生成大量的对象。

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

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

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

调用方法时传递的参数及调用中创建的临时变量保存在栈(Stack)中,速度较快。其他变量,如静态变量、实例变量都在堆(Heap)中创建,速度较慢。访问静态变量和实例变量将会比访问局部变量多耗费 2-3 个时钟周期。如果一个变量需要经常访问,那么你就需要考虑这个变量的作用域了。static? local? 还是实例变量?

例子:  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
2
3
4
5
6
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修饰符的类是不可派生的。如果指定一个类为final,则该类所有的方法都是final。JAVA编障器会寻找机会内联(inIine)所有的final方法。此举能够提升程序性能。使用final、static、private的方法是不能被覆盖的,JAVA不需要在稃序运行的时候动态关联实现方法,从而节省了运行时间。

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

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

1
2
3
4
5
6
class maf {
    public void setsize (int size) {
         _size = size;
    }
    private int _size;
}

更正:   

1
2
3
4
5
6
class daf_fixed {
    final public void setsize (int size) {
         _size = size;
    }
    private int _size;
}

7、避免不需要的 instanceof 操作  

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

1
2
3
4
5
6
7
8
9
10
11
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
2
3
4
5
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
2
3
4
5
6
7
8
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
2
3
4
5
6
7
class dog extends unc {
    void method () {
        dog dog = new dog();
        unc animal = dog;
        object o = dog;
    }
}

二、JavaI/O技巧

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

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

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

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

当使用Unicode字符串时,Write类的开销比较大。因为它要实Uoicode到字节(byte)的转换。凶此,如果可能的话,在使_}}j Write类之前就实现转换或用OutputStream类代替Writer娄来使用。

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

1个char用2个字节保存字符,而byte只需要1个,因此用byte保存字符消耗的内存和需要执行的机器指令更少。更重要的是,用byte避免了进行Unicode转换。因此,如果可能的话,应尽量使用byte替代char。

4、有缓冲的块操作I/O要比缓冲的流字符I/O快。

对于字符I/O,虽然缓冲流避免了每次读取字符时的系统调用开销,但仍需要一次或多次方法调用。带缓冲的块I/O比缓冲流I/O快2到4倍,比无缓冲的I/O快4到40倍。

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

当序列化一个类或对象时,对干那些原子类型(atomic)或可以重建的元素,要标识为transient类型,这样就不用每一次都进行序列化。如果这砦序列化的对象要在网络上传输,这一小小的改变对性能会有很大的提高。

6、在finally 块中关闭stream 

程序中使用到的资源应当被释放,以避免资源泄漏。这最好在 finally 块中去做。不管程序执行的结果如何,finally 块总是会执行的,以确保资源的正确关闭。  
例子:  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 块  

三、异常(Exceptions)使用技巧

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

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

如果可以用if、while等逻辑语句来处理,那么就尽可能的不用try/catch语句

2、尽可能重用异常

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

3、将try/catch 块移出循环  

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

1
2
3
4
5
6
7
8
9
10
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
2
3
4
5
6
void method (fileinputstream fis) {
       try {
           for (int i = 0; i < size; i++) {                 _sum += fis.read();
           }
       catch (exception e) {}
   }

四、线程使用技巧

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

生成和启动新线程是个相对较慢的过程,生成大量新线程会严重影响程序性能。通过使用线程池,由线程池管理器(thread pool manager)来生成新线程或分配现有线程,节省生成线程的时间。

2、防止过多的同步

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

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

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

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

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

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

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

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

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

1
2
3
4
5
6
7
8
9
10
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 (55);
}

更正:不要在循环体中调用同步方法,如果必须同步的话,推荐以下方式:  

1
2
3
4
5
6
7
8
9
10
11
12
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 (55);
}

五、其它常用技巧

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

       "/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。  
例子:  
1
2
3
4
5
6
7
8
9
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
2
3
4
5
6
7
8
9
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
2
3
4
5
6
7
8
9
10
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
2
3
4
5
6
7
8
9
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, 0100);
    }
}

4、使用复合赋值运算符

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

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

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

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

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

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

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

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

可以利用Statement类的addBatch()或executeBatch法成批地提交sql语句,以节省网络传输开销。在执行大量相似语句时,可以使用PreParedStatement—类,它可以一次性编译语句并多次执行,用参数最后执行的sql语句。

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

这似乎是每个程序员都知道的基本原则,没有必出,但很多人往往忽略一些细节。如下列代码:

1
2
3
4
Vector aVector= ...;
for(int i=0;i<aVector size();i++)(
System out println(aVector.elementAt(i).toStringO);
}


这段代码中没循环一次就要调用aVector.size()方法,aVector的长度不变的话,可以改为一下代码:

1
2
3
4
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
2
3
4
5
6
7
8
9
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
2
public vector v = new vector(20);  
    public hashtable hash = new hashtable(10);

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

用一个字符作为参数调用 startswith()也会工作的很好,但从性能角度上来看,调用用 string api 无疑是错误的!  
例子:  
1
2
3
4
5
6
7
public class pcts {
    private void method(string s) {
        if (s.startswith("a")) { // violation
            // ...
        }
    }
}    
更正 :将'startswith()' 替换成'charat()'.  
1
2
3
4
5
6
7
public class pcts {
    private void method(string s) {
        if ('a' == s.charat(0)) {
            // ...
        }
    }
}

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

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

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

 14、对于常量字符串,用'String' 代替 'StringBuffer'   

常量字符串并不需要动态改变长度。  
例子:  
1
2
3
4
5
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
2
3
4
5
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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; <span style="white-space:pre;"> </span>}
    }
}
更正:  
1
2
3
4
5
6
7
8
9
10
public class if {
    public int method(boolean isdone) {
        return (isdone ? 0 10);
    }
 
    void method(boolean istrue) {
    <span style="white-space:pre;"> </span>_value = (istrue ? 0 1);       // comp<span style="white-space:pre;">  </span>}
    private int _value = 0;
 
}

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

在循环体中实例化临时变量将会增加内存消耗  
例子:          
1
2
3
4
5
6
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
2
3
4
5
6
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
2
3
4
5
6
public class rsbc {
    void method () {
        stringbuffer buffer = new stringbuffer(); // violation
        buffer.append ("hello");
    }
 }    
更正:为 StringBuffer 提供寝大小。          
1
2
3
4
5
6
7
public class rsbc {
    void method () {
        stringbuffer buffer = new stringbuffer(max);
        buffer.append ("hello");
    }
    private final int max = 100;
}

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

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

20、与一个接口进行instanceof 操作  

基于接口的设计通常是件好事,因为它允许有不同的实现,而又保持灵活。只要可能,对一个对象进行 instanceof 操作,以判断它是否某一接口要比是否某一个类要快。  
例子:  
1
2
3
4
5
6
7
8
9
public class insof {
    private void method (object o) {
        if (o instanceof interfacebase) { }  // better
        if (o instanceof classbase) { }   // worse.
    }
}
  
class classbase {}
interface interfacebase {}
原文地址:https://www.cnblogs.com/barrywxx/p/4399339.html