Background
尝试进行一个简单的实验,看看传统的 if
语句检查 null 是否比 Apache Commons Lang StringUtils isEmpty
/isBlank
更快。
为了运行此测试,我使用 Java 8u102
、Apache Commons Lang 版本 3.4
并在 Windows 10 64 位上运行。
The Test Code
下面是使用标准主类的测试代码:
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);
The Result
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
令我非常惊讶的是, native 方法比 Apache Commons Lang 库快得多。
The Question
谁能指出我的结果是否是决定性的?我的测试是否有可能是错误的,因此会出现这样的结果?谢谢。
最佳答案
注意:我强烈建议您查看 JMH http://openjdk.java.net/projects/code-tools/jmh/用于 Java 中的 microbenchamrk。
<小时/>加载类时需要时间,在 String 示例中,该类已经加载。
编写基准测试时,您需要
- 让代码预热至少 2 - 30 秒(取决于代码的复杂性)
- 运行测试至少 5 到 30 秒。
- 删除所有打印内容。写入控制台通常比大多数基本操作慢 10,000 倍。
任何几毫秒长的测试都可能是类似于加载类的时间。
Is there any chances that my test is wrong therefore such result?
您正在测试的操作应该是几十纳秒。 6 毫秒的结果可能会误差约 100,000 倍。
关于java - Apache Commons Lang StringUtils 较慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39071372/