Java 判断字符串是否为空的三种方法性能比较

以下是 Java 判断字符串是否为空的三种方法.

 

方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低.
方法二: 比较字符串长度, 效率高.

 

方法三: Java SE 6.0 才开始提供的方法, 效率和方法二几乎相等, 但出于兼容性考虑, 推荐使用方法二.

 

以下代码在我机器上的运行结果: (机器性能不一, 仅供参考)
method 1 use time: 156ms
method 2 use time: 32ms
method 3 use time: 31ms


package test;

import junit.framework.TestCase;


public class JavaTest extends TestCase {
   
    //字符空判断
    public void CompareStringNothing(){
        String str = "";
        long len = 10000000;

        long startTime1 = System.currentTimeMillis();
        //1
        for(long i = 0; i < len; i++) {
            //此方法最慢
            if(str == null || str.equals(""));
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("method 1 use time: "+ (endTime1 - startTime1) +"ms");

       




    
        long startTime2 = System.currentTimeMillis();
        for(long i = 0; i < len; i++) {
            if(str == null || str.length() <= 0);
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("method 2 use time: "+ (endTime2 - startTime2) +"ms");

       





        long startTime3 = System.currentTimeMillis();         
        for(long i = 0; i < len; i++) {
            if(str == null || str.isEmpty());
        }
        long endTime3 = System.currentTimeMillis();
        System.out.println("method 3 use time: "+ (endTime3 - startTime3) +"ms");

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值