>  기사  >  Java  >  Java의 프로그램 성능 최적화 예

Java의 프로그램 성능 최적화 예

黄舟
黄舟원래의
2017-07-27 10:31:571130검색

1. 루프 조건에서 복잡한 표현식 사용을 피하세요

컴파일 최적화가 없으면 루프 조건이 루프에서 반복적으로 계산됩니다. 복잡한 표현식을 사용하지 않으면 루프 조건 값이 변경되지 않습니다. , 프로그램이 더 빠르게 실행됩니다.

예:

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++)
            ; // ...
    }
}



2. '벡터' 및 '해시테이블'의 초기 크기를 정의합니다.

jvm은 크기를 확장할 때 더 큰 크기를 다시 만들어야 합니다. 벡터 배열의 경우 원본 배열의 내용을 복사하고 마지막으로 원본 배열을 재활용합니다. 벡터 용량의 확장은 시간이 많이 걸리는 문제임을 알 수 있다.
기본 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);

3. finally 블록에서 스트림을 닫으세요

프로그램에 사용된 리소스는 리소스 유출을 방지하기 위해 해제되어야 합니다. 이 작업은 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 = 0;
            while (fis.read () != -1)
                count++;
            system.out.println (count);
            fis.close ();
        } catch (filenotfoundexception e1) {
        } catch (ioexception e2) {
        }
    }
}

수정:
마지막 캐치 뒤에 finally 블록을 추가하세요

4 배열을 복사하기 위해 반복하는 대신 '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);
    }
}



5 인스턴스의 변수에 액세스하는 getter/setter 메서드를 "최종"으로 만듭니다

간단한 getter/setter 메서드를 최종으로 만들어야 합니다. 이 메서드는 오버로드되지 않으므로 "인라인"될 수 있다고 컴파일러에 알립니다. 예:

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;
}


6. 불필요한 인스턴스 작업을 피하세요.


정적 유형의 경우 왼쪽의 객체가 오른쪽의 객체와 같으면, instanceof 표현식은 항상 true를 반환합니다. ㅋㅋㅋ        인스턴스 오브(instanceof)의 도움으로.             

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");
    }
}



7. 불필요한 스타일링 작업을 피하세요


모든 클래스는 객체에서 직접 또는 간접적으로 상속받습니다. 마찬가지로, 모든 하위 클래스는 암시적으로 상위 클래스와 "동일"합니다. 그러면 하위 클래스에서 상위 클래스로 모델링하는 작업이 필요하지 않습니다. R 예: re

class dog extends uiso {
    void method () {
        dog d;
        system.out.println ("dog is an uiso");
        system.out.println ("uiso is an uiso");
    }
}

수정:

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.
    }
}


, 문자 하나만 찾은 경우 startwith() 대신 차트()를 사용하세요.



문자를 매개변수로 사용하여 startwith( ) 좋습니다. 하지만 성능 관점에서 볼 때 String API를 호출하는 것은 의심할 여지 없이 잘못된 것입니다!

예:

class dog extends unc {
    void method () {
        dog dog = new dog();
        unc animal = dog;
        object o = dog;
    }
}
Correction




'' '' '' '' 대신 Shift 연산을 사용하세요. 'a / b' 작업



"/"는 매우 "비용이 많이 드는" 작업이므로 교대 작업을 사용하는 것이 더 빠르고 효율적입니다.


예:

public class pcts {
    private void method(string s) {
        if (s.startswith("a")) { // violation
            // ...
        }
    }
}
수정:
public class pcts {
    private void method(string s) {
        if (&#39;a&#39; == s.charat(0)) {
            // ...
        }
    }
}



10 'a * b' 대신 Shift 연산을 사용하세요.


위와 동일합니다.

[i]그러나 저는 개인적으로 이 방법이 매우 큰 루프 내에 있지 않고 성능이 매우 중요하며 자신이 무엇을 하고 있는지 알고 있지 않는 한에만 사용해야 한다고 생각합니다. 그렇지 않으면 성능 향상으로 인해 프로그램의 가독성이 떨어지는 것은 비경제적입니다.

예:

public class sp {
    public static final int num = 16;
    public void calculate(int a) {
        int p = a / 4;            // should be replaced with "a >> 2".
        int p2 = a / 8;         // should be replaced with "a >> 3".
        int temp = a / 3;
    }
}
수정:

public class sp {
    public static final int num = 16;
    public void calculate(int a) {
        int p = a >> 2;  
        int p2 = a >> 3;
        int temp = a / 3;       // 不能转换成位移操作
    }
}



11 문자열을 추가할 때 문자열에 문자가 하나만 있는 경우 "" 대신 ''를 사용하세요


예:

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;
    }
}
Co 정정: 한 문자열을 ''로 바꾸세요
public class str {
    public void method(string s) {
        string string = s + &#39;d&#39;
        string = "abc" + &#39;d&#39;   
    }
}


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

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

例子:

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);
}

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

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);
}



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

把try/catch块放入循环体内,会极大的影响性能,如果编译jit被关闭或者你所使用的是一个不带jit的jvm,性能会将下降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块移出循环        

 void method (fileinputstream fis) {
        try {
            for (int i = 0; i < size; i++) {
                _sum += fis.read();
            }
        } catch (exception e) {}
    }

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

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

例子:

public class ueq
{
    boolean method (string string) {
        return string.endswith ("a") == true;   // violation
    }
}

更正:

class ueq_fixed
{
    boolean method (string string) {
        return string.endswith ("a");
    }
}

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

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

public class usc {
    string method () {
        stringbuffer s = new stringbuffer ("hello");
        string t = s + "world!";
        return t;
    }
}

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

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

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

例子:

public class ust {
    void parsestring(string string) {
        int index = 0;
        while ((index = string.indexof(".", index)) != -1) {
            system.out.println (string.substring(index, string.length()));
        }
    }
}

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

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

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;" 结构

例子:

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;
}


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

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

例子:        

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);
        }
    }
}


        
更正:        
在循环体外定义变量,并反复使用        

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

例子:        

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;
}


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

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

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()方法:        

void getsum (int[] values) {
    int sum = _sum;  // temporary local variable.
    for (int i=0; i < value.length; i++) {
        sum += value[i];
    }
    _sum = sum;
}


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

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

例子:

public class dun {
    boolean method (boolean a, boolean b) {
        if (!a)
            return !a;
        else
            return !b;
    }
}


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

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


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

例子:

public class insof {
    private void method (object o) {
        if (o instanceof interfacebase) { }  // better
        if (o instanceof classbase) { }   // worse.
    }
}

class classbase {}
interface interfacebase {}


위 내용은 Java의 프로그램 성능 최적화 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.