【发布时间】:2016-12-28 12:33:25
【问题描述】:
背景
尝试一个简单的实验来确定检查 null 的传统 if 语句是否比 Apache Commons Lang StringUtils isEmpty/isBlank 更快。
为了运行这个测试,我使用Java 8u102,Apache Commons Lang 版本3.4 并在 Windows 10 64 位上运行。
测试代码
以下是使用标准主类的测试代码:
System.out.println("Testing of StringUtils.isNotNull vs native java method");
System.out.println("======================================================");
System.out.println("Testing conventional method...");
final List<String> array = new ArrayList<String>();
array.add("1");
array.add(null);
array.add("3");
array.add(null);
array.add("5");
long start = System.currentTimeMillis();
for (String s : array) {
System.out.println(s == null ? "yes" : "no");
}
System.out.println(System.currentTimeMillis() - start);
System.out.println("Testing StringUtils method...");
start = System.currentTimeMillis();
for (String s : array) {
System.out.println(StringUtils.isBlank(s) ? "yes" : "no");
}
System.out.println(System.currentTimeMillis() - start);
结果
Testing of StringUtils.isNotNull vs native java method
======================================================
Testing conventional method...
no
yes
no
yes
no
0
Testing StringUtils method...
no
yes
no
yes
no
6
令我惊讶的是,本机方法比 Apache Commons Lang 库快得多。
问题
谁能指出我的结果是否确凿?有没有可能我的测试是错误的,因此会有这样的结果?谢谢。
【问题讨论】:
-
好吧,look at the source。似乎需要更长的时间
-
我猜开销是用于双重/三重检查。
-
您的代码正在使用 StringUtils#isBlank,它不仅仅进行空测试,它还检查空 "" 字符串和仅空格字符串。