比较两个字符串空,两种方法性能比较

本文通过实验对比了str.isEmpty()和.equals(str)两种字符串判空方法的效率,结果显示str.isEmpty()方法明显更快。
测试 str.isEmpty()和 "".equals(str)两种判断的效率
比较次数999999999
str.isEmpty()用时2735(2.7秒)
"".equals(str)用时10516(10秒)

差别如此之大

public class Test4
{
    public static void main(String[] args)
    {
        long times = 999999999;
        String str = "";

        long a1 = System.currentTimeMillis();
        for (long i = 0; i < times && str.isEmpty(); i++)
        {
            // System.out.println(str.isEmpty());
        }
        long a2 = System.currentTimeMillis();
        System.out.println("str.isEmpty() times: " + (a2 - a1));

        long b1 = System.currentTimeMillis();
        for (long i = 0; i < times && "".equals(str); i++)
        {
            // System.out.println("".equals(str));
        }
        long b2 = System.currentTimeMillis();
        System.out.println("\"\".equals(str) times: " + (b2 - b1));
    }
}
输出结果:

str.isEmpty() times: 2735
"".equals(str) times: 10516


其实看下源码很快就发现问题所在

public boolean isEmpty() {
	return count == 0;
    }

public boolean equals(Object anObject) {
	if (this == anObject) {
	    return true;
	}
	if (anObject instanceof String) {
	    String anotherString = (String)anObject;
	    int n = count;
	    if (n == anotherString.count) {
		char v1[] = value;
		char v2[] = anotherString.value;
		int i = offset;
		int j = anotherString.offset;
		while (n-- != 0) {
		    if (v1[i++] != v2[j++])
			return false;
		}
		return true;
	    }
	}
	return false;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值