java判断字符串是否为空的方法总结

来源:互联网 发布:ipad软件开发 编辑:程序博客网 时间:2024/06/15 08:04

方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低:

                                    if(s == null ||"".equals(s));

方法二: 比较字符串长度, 效率高, 是我知道的最好一个方法:

                      if(s == null || s.length() <= 0);

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

                     if(s == null || s.isEmpty());

方法四: 这是一种比较直观,简便的方法,而且效率也非常的高,与方法二、三的效率差不多:

                     if (s == null || s == "");

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Zifuchuanpankong {
    public static final String  STR = "1111111";
    public static void function1(){
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            if (STR == null || "".equals(STR)) {
                ;
            }
        }
        long endTime = System.currentTimeMillis();
        System.err.println("[STR == null || \"\".equals(STR)] 耗时:"+(endTime-startTime)+" ms");
    }
    public static void function2(){
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            if (STR == null || STR.length()<=0) {
                ;
            }
        }
        long endTime = System.currentTimeMillis();
        System.err.println("[STR == null || STR.length()<=0] 耗时:"+(endTime-startTime)+" ms");
    }
    public static void function3(){
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            if (STR == null || STR.isEmpty()) {
                ;
            }
        }
        long endTime = System.currentTimeMillis();
        System.err.println("[STR == null || STR.isEmpty()] 耗时:"+(endTime-startTime)+" ms");
    }
    public static void function4(){
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            if (STR == null || STR == "") {
                ;
            }
        }
        long endTime = System.currentTimeMillis();
        System.err.println("[STR == null || STR == \"\"] 耗时:"+(endTime-startTime)+" ms");
    }
 
    public static void main(String[] args) {
        function1();
        function2();
        function3();
        function4();
    }
}

[STR == null || "".equals(STR)] 耗时:51 ms
[STR == null || STR.length()<=0] 耗时:7 ms
[STR == null || STR.isEmpty()] 耗时:9 ms
[STR == null || STR == ""] 耗时:4 ms

原创粉丝点击