java 空字条串空判断 效率

引用:http://www.cnblogs.com/suman/archive/2010/10/26/1861521.html

以下是 Java 判断字符串是否为空的三种方法.
方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低.
方法二: 比较字符串长度, 效率高, 是我知道的最好一个方法.
方法三: Java SE 6.0 才开始提供的方法, 效率和方法二几乎相等, 但出于兼容性考虑, 推荐使用方法二.

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

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
public class CompareStringNothing {
    String s = "";
    long n = 10000000;
  
    private void function1() {
        long startTime = System.currentTimeMillis();
  
        for(long i = 0; i < n; i++) {
            if(s == null || s.equals(""));
        }
        long endTime = System.currentTimeMillis();
  
        System.out.println("function 1 use time: "+ (endTime - startTime) +"ms");
    }
  
    private void function2() {
        long startTime = System.currentTimeMillis();
  
        for(long i = 0; i < n; i++) {
            if(s == null || s.length() <= 0);
        }
        long endTime = System.currentTimeMillis();
  
        System.out.println("function 2 use time: "+ (endTime - startTime) +"ms");
    }
  
    private void function3() {
        long startTime = System.currentTimeMillis();
  
        for(long i = 0; i < n; i++) {
            if(s == null || s.isEmpty());
        }
        long endTime = System.currentTimeMillis();
  
        System.out.println("function 3 use time: "+ (endTime - startTime) +"ms");
    }
  
    public static void main(String[] args) {
        CompareStringNothing com = new CompareStringNothing();
        com.function1();
        com.function2();
        com.function3();
    }
}
 
分类: JAVA
原文地址:https://www.cnblogs.com/sode/p/2501883.html