Java中Long類型相等對(duì)比性能分析

Long 相等對(duì)比分析

四種對(duì)比方案

小于128L可以直接用==判斷,存在風(fēng)險(xiǎn)不建議直接使用==

    Long a = 200L;
        Long b = 200L;
        System.out.println(a.equals(b));
        System.out.println(a.longValue()==b.longValue());
        System.out.println(a-b==0);
        System.out.println(a.compareTo(b) == 0);

檢測(cè)項(xiàng)目代碼時(shí)發(fā)現(xiàn)了另外的一種寫法

oneBigNum.toString().equals(twoBigNum.toString()

一時(shí)興起,對(duì)性能進(jìn)行了一下測(cè)試(有點(diǎn)孔乙己的感覺(jué))

package org.example;

public class Main {
    public static void main(String[] args) {
        Long oneNum=100L;
        Long twoNum=100L;
        Long oneCommNum127=127L;
        Long twoCommNum127=127L;

        Long oneCommNum128=128L;
        Long twoCommNum128=128L;
        Long oneBigNum=10000L;
        Long twoBigNum=10000L;

        int times=100*100*10000;

        System.out.println("equals times---> "+times);

        long t1=System.currentTimeMillis();
        for (int i=0;i<times;i++){
            boolean a=oneBigNum.equals(twoBigNum);
        }
        long t2=System.currentTimeMillis();

        System.out.println("oneBigNum.equals(twoBigNum)--耗時(shí)---> "+(t2-t1));
        t1=System.currentTimeMillis();
        for (int i=0;i<times;i++){
            boolean a=oneBigNum.toString().equals(twoBigNum.toString());
        }
        t2=System.currentTimeMillis();

        System.out.println("oneBigNum.toString().equals(twoBigNum.toString())--耗時(shí)---> "+(t2-t1));

        t1=System.currentTimeMillis();
        for (int i=0;i<times;i++){
            boolean a=oneBigNum.longValue()==twoBigNum.longValue();
        }
        t2=System.currentTimeMillis();

        System.out.println("oneBigNum.longValue()==twoBigNum.longValue()--耗時(shí)---> "+(t2-t1));

        t1=System.currentTimeMillis();
        for (int i=0;i<times;i++){
            boolean a=0==oneBigNum-twoBigNum;
        }
        t2=System.currentTimeMillis();

        System.out.println("0==oneBigNum-twoBigNum--耗時(shí)---> "+(t2-t1));

        t1=System.currentTimeMillis();
        for (int i=0;i<times;i++){
            boolean a=0==oneBigNum.compareTo(twoBigNum);
        }
        t2=System.currentTimeMillis();

        System.out.println("oneBigNum.compareTo(twoBigNum)--耗時(shí)---> "+(t2-t1));
    }
}

輸出

equals times---> 100000000
oneBigNum.equals(twoBigNum)--耗時(shí)---> 6
oneBigNum.toString().equals(twoBigNum.toString())--耗時(shí)---> 6005
oneBigNum.longValue()==twoBigNum.longValue()--耗時(shí)---> 4
0==oneBigNum-twoBigNum--耗時(shí)---> 4
oneBigNum.compareTo(twoBigNum)--耗時(shí)---> 4

總結(jié)

包裝類已經(jīng)提供了equals方法盡量采用其提供的方法進(jìn)行相等對(duì)比

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

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

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