尝试一个简单的实验,以找出是否传统if
语句来检查null是比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
要我已经ry惊讶于本地方法比Apache Commons Lang库快得多。
问题
谁能指出,如果我的结果是确定的?我的测试是否有错误,因此会有这样的结果?谢谢。
那么,[看看源代码](https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html)。似乎需要更长的时间 – Li357
我猜测开销是双重/三重检查使用。 – d4v1dv00
你的代码使用的StringUtils#isBlank不仅仅是空测试,它检查空的“”字符串和只有空格字符串。 – benbenw