java String变量判空 效率

Java中的String为引用类型,我们经常遇到判空的情况,str==null判断该字符串是否为null(空引用类型对象)。
str.isEmpty(),判断该字符串是否为空字符串;
str.equals(""),判断该字符串是否为空字符串。
isEmpty()和equals("")都可以判断该字符串是否为空字符串,但是equals()方法是根据str的hashcode来进行比较的,经测试,效率不如isEmpty()高。

isEmpty的实现机制就是判断str.length==0,

所以论效率而言,str.length==0高于str.isEmpty()高于equals("").

package com.supan.test;
import junit.framework.TestCase;
public class IsStringEmpty extends TestCase {
//效率第三
public void testXiaolv1()
{
String str1 = "chenchaoyang";
Long satrt = System.currentTimeMillis();
System.out.println(satrt);
if(str1 != null && !str1.equals(""))
{
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
}
Long end = System.currentTimeMillis();
System.out.println(end);
System.out.println(satrt - end);
}

//效率第二
public void testXiaolv2()
{
String str1 = "chenchaoyang";
Long satrt = System.currentTimeMillis();
System.out.println(satrt);
if(str1 != null && !str1.isEmpty())
{
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
}
Long end = System.currentTimeMillis();
System.out.println(end);
System.out.println(satrt - end);
}

//效率最高
public void testXiaolv3()
{
String str1 = "chenchaoyang";
Long satrt = System.currentTimeMillis();
System.out.println(satrt);
if(str1 != null && str1.length() > 0)
{
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
System.out.println("chenchaoyang");
}
Long end = System.currentTimeMillis();
System.out.println(end);
System.out.println(satrt - end);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值