直接創(chuàng)建對象和直接賦值方式創(chuàng)建對象性能比較

public class Test {
    
    public static void directSetValue(int times){
        BeTest test = new BeTest();
        for(int i=0;i<times;++i){
            test.setId(i);
            test.setName("dsfs");
            test.setName2("sdf");
            test.setName3("et");
        }
    }
    public static void createObject(int times){
        for(int i=0;i<times;++i){
            new BeTest(i,"dsfs","sdf","et");
        }
    }
    
    public static void cloneObject(int times){
        BeTest test = new BeTest(1,"dsfs","sdf","et");
        for(int i=0;i<times;++i){
            test.clone();
        }
    }
    
    public static void main(String args[]){
        int times=100000000;
        long current=System.currentTimeMillis();
        directSetValue(times);
        long useTime = System.currentTimeMillis()-current;
        current=System.currentTimeMillis();
        createObject(times);
        long useTime2 = System.currentTimeMillis()-current;
        current=System.currentTimeMillis();
        cloneObject(times);
        long useTime3 = System.currentTimeMillis()-current;
        System.err.println("復(fù)值方式構(gòu)建對象:"+useTime+"\n直接創(chuàng)建對象:"+useTime2+
                "\n克隆方式創(chuàng)建對象:"+useTime3);
    }
}
class BeTest implements Cloneable{
    private Integer id;
    private String name;
    private String name2;
    private String name3;
    public void setId(Integer id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setName2(String name2) {
        this.name2 = name2;
    }
    public void setName3(String name3) {
        this.name3 = name3;
    }
    public BeTest() {
        super();
    }
    public BeTest(Integer id, String name, String name2, String name3) {
        super();
        this.id = id;
        this.name = name;
        this.name2 = name2;
        this.name3 = name3;
    }
    public Object clone(){
        Object t=null;
        try {
            t= super.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }   
}

結(jié)果顯示:
復(fù)值方式構(gòu)建對象:481
直接創(chuàng)建對象:361
克隆方式創(chuàng)建對象:651
總結(jié):如果不考慮內(nèi)存,直接創(chuàng)建對象,比通過對象池方式或克隆對象方式獲取對象更加高效

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容