Long 相等对比分析
四种对比方案
小于128L可以直接用==判断,存在风险不建议直接使用==
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);
检测项目代码时发现了另外的一种写法
oneBigNum.toString().equals(twoBigNum.toString()
一时兴起,对性能进行了一下测试(有点孔乙己的感觉)
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)--耗时---> "+(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())--耗时---> "+(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()--耗时---> "+(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--耗时---> "+(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)--耗时---> "+(t2-t1));
}
}
输出
equals times---> 100000000
oneBigNum.equals(twoBigNum)--耗时---> 6
oneBigNum.toString().equals(twoBigNum.toString())--耗时---> 6005
oneBigNum.longValue()==twoBigNum.longValue()--耗时---> 4
0==oneBigNum-twoBigNum--耗时---> 4
oneBigNum.compareTo(twoBigNum)--耗时---> 4
总结
包装类已经提供了equals方法尽量采用其提供的方法进行相等对比
网友评论