代码之家  ›  专栏  ›  技术社区  ›  Matt Ball

我应该使用string.isEmpty()还是“.equals(string)?

  •  162
  • Matt Ball  · 技术社区  · 15 年前

    我通常会和一个 string == null

    String s = /* whatever */;
    ...
    if (s == null || "".equals(s))
    {
        // handle some edge case here
    }
    

    if (s == null || s.isEmpty())
    {
        // handle some edge case here
    }
    

    在那张纸条上-是吗 isEmpty() return this.equals(""); return this.length() == 0; ?

    6 回复  |  直到 5 年前
        1
  •  252
  •   Michael Mrozek    15 年前

    它的主要好处是 "".equals(s) 你不知道吗 需要 空检查( equals false s 如果为null(或者正在检查它),我肯定会使用 s.isEmpty() s

        2
  •  83
  •   Jasper wontondon    14 年前

    String.equals("") 实际上比一个 isEmpty() 打电话。字符串存储在构造函数中初始化的计数变量,因为字符串是不可变的。

    isEmpty()

    isEmpty() 实际上会少做很多!这是件好事。

        3
  •  17
  •   Fabian Steeg    15 年前

    除了提到的其他问题外,您可能还需要考虑一件事: isEmpty()

        4
  •  15
  •   Android Killer    12 年前

    您可以使用apachecommons StringUtils isEmpty()或isNotEmpty()。

        5
  •  2
  •   Jasper wontondon    14 年前

    其实没关系。 "".equals(str) 在我看来更清楚。

    isEmpty() 退货 count == 0 ;

        6
  •  2
  •   Wolfson rlibby    5 年前

    Tester 可以测试性能的类:

    public class Tester
    {
        public static void main(String[] args)
        {
            String text = "";
    
            int loopCount = 10000000;
            long startTime, endTime, duration1, duration2;
    
            startTime = System.nanoTime();
            for (int i = 0; i < loopCount; i++) {
                text.equals("");
            }
            endTime = System.nanoTime();
            duration1 = endTime - startTime;
            System.out.println(".equals(\"\") duration " +": \t" + duration1);
    
            startTime = System.nanoTime();
            for (int i = 0; i < loopCount; i++) {
                text.isEmpty();
            }
            endTime = System.nanoTime();
            duration2 = endTime - startTime;
            System.out.println(".isEmpty() duration "+": \t\t" + duration2);
    
            System.out.println("isEmpty() to equals(\"\") ratio: " + ((float)duration2 / (float)duration1));
        }
    }
    

    我发现使用 .isEmpty() 花了大约一半的时间 .equals("") .