您的位置:首页 > 其它

测试null和str相等比较的性能差别问题

2008-11-18 16:39 357 查看
原文地址:http://www.java2000.net/p12096

到底是 str==null 快一些还是 null==str 快一些呢?
我们还是亲自测试一下看看吧,大家也可以看看代码,然后自己测试一下,不要人云亦云。包括我自己的结论也是这样,请有疑虑的人亲自测试,看结果。

先看测试代码
/**
* 测试传说中的null==str的性能问题。<br>
* 据说 null==str比str==null的性能高一些。<br>
* 我们来测试一下看看
*
* @author 老紫竹 J***A世纪网(java2000.net)
*
*/
public class Test {
static int TIMES = 1000000000;
static String str = "J***A2000.net";

public static void main(String[] args) {
long t1;
long t2;
// 测试10轮

for (int i = 0; i < 10; i++) {
t1 = test1();
t2 = test2();
System.out.printf("str == null:%13d/t", t1);
System.out.printf("null == str:%13d/t", +t2);
System.out.printf("Diff=%13d", t2 - t1);
System.out.println();
// 顺序颠倒一下
t2 = test2();
t1 = test1();
System.out.printf("str == null:%13d/t", t1);
System.out.printf("null == str:%13d/t", +t2);
System.out.printf("Diff=%13d", t2 - t1);
System.out.println();
}

}

public static long test1() {
long t1 = System.nanoTime();
for (int i = 0; i < TIMES; i++) {
if (str == null) {
;
}
}
return System.nanoTime() - t1;
}

public static long test2() {
long t1 = System.nanoTime();
for (int i = 0; i < TIMES; i++) {
if (null == str) {
;
}
}
return System.nanoTime() - t1;

}
}

我的测试结果
str == null: 1331211649 null == str: 1306476382 Diff= -24735267
str == null: 1325049972 null == str: 1310683341 Diff= -14366631
str == null: 1321184396 null == str: 1314800066 Diff= -6384330
str == null: 1308572459 null == str: 1310631659 Diff= 2059200
str == null: 1322850530 null == str: 1312672142 Diff= -10178388
str == null: 1310835595 null == str: 1312089385 Diff= 1253790
str == null: 1324557172 null == str: 1311582059 Diff= -12975113
str == null: 1311757780 null == str: 1329927686 Diff= 18169906
str == null: 1325011978 null == str: 1305032064 Diff= -19979914
str == null: 1325790010 null == str: 1309495201 Diff= -16294809
str == null: 1308165144 null == str: 1316338529 Diff= 8173385
str == null: 1321638644 null == str: 1310619646 Diff= -11018998
str == null: 1305769309 null == str: 1306789550 Diff= 1020241
str == null: 1324110187 null == str: 1307757550 Diff= -16352637
str == null: 1311276712 null == str: 1309109957 Diff= -2166755
str == null: 1323087432 null == str: 1308201741 Diff= -14885691
str == null: 1305018096 null == str: 1304627264 Diff= -390832
str == null: 1326120778 null == str: 1314136852 Diff= -11983926
str == null: 1312848141 null == str: 1306828382 Diff= -6019759
str == null: 1319538097 null == str: 1313048725 Diff= -6489372

我的结论:

1 测试10亿次,最大的差别在0.024秒

2 整体上 null==str的速度快于str==null

3 个别情况则正好相反

4 个人认为,这个数量级的差距,我个人就不考虑了。呵呵呵!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: