先看再点赞,给自己一点思考的时间,微信搜索【果汁简历】公众号,获取更多内容。 本文 GitHub
https://github.com/juice-resume/java-programming
已收录,里面还有一线大厂整理的面试题,以及我的系列文章
文章目录
- String.replace vs StringUtils.replace
- 什么是 JMH
- 使用 JMH 测试 replace
- JMH基本概念
- 源码 & 课后题
String.replace vs StringUtils.replace
字符串的 replace
是我们平时最常用的操作了,那么你用对了吗?我们下面就快速的比较一下 String.replace
和 StringUtils.replace
的性能,你就会发现平时用的对不对了。
Benchmark Mode Cnt Score Error Units
longString1Match thrpt 21 1065385.376 ± 163542.395 ops/s
longString1MatchUtils thrpt 21 5796658.817 ± 402075.454 ops/s
longStringNMatch thrpt 21 836951.534 ± 184212.932 ops/s
longStringNMatchUtils thrpt 21 2604916.198 ± 1151573.761 ops/s
longStringNoMatch thrpt 21 2664613.208 ± 812092.909 ops/s
longStringNoMatchUtils thrpt 21 13064807.201 ± 5216438.357 ops/s
shortString1Match thrpt 21 1666278.062 ± 847582.653 ops/s
shortString1MatchUtils thrpt 21 8487720.328 ± 4039195.570 ops/s
shortStringNMatch thrpt 21 2160392.894 ± 326624.549 ops/s
shortStringNMatchUtils thrpt 21 7579329.122 ± 1555644.322 ops/s
shortStringNoMatch thrpt 21 4644501.698 ± 1052814.151 ops/s
shortStringNoMatchUtils thrpt 21 92366435.842 ± 31333158.039 ops/s
上面的内容是通过 JMH
输出的基准测试比较,我们可以清楚的看到 String.replace
和 StringUtils.replace
的差距是非常大,尤其是没有匹配项的时候,我们可以简单通过源码查看其原因,StringUtils
在替换的时候会优先判断是否有匹配然后再循环,这样减少了很多无用的操作,当然 JDK9
以后也做了这个功能的优化,所以如果你使用的是 9+ 可以忽略这个性能问题。
int end = searchText.indexOf(searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
其次呢,JDK 的 replace 里面使用的正则也是一个非常耗时测操作。
return Pattern
.compile(target.toString(), Pattern.LITERAL)
.matcher(this)
.replaceAll(Matcher.quoteReplacement(replacement.toString()));
好了说到这里基本知道平时替换字符串怎么做了吧,这个可不是大题小做,正所谓不积跬步无以至千里,那么接下来就来说说我们上文中的测试是怎么实现的。
什么是 JMH
Java Microbenchmark Harness, 由JIT开发人员开发的,于2013年发布的一款基于Java的微基准测试工具,现已归于JDK。官网:
http://openjdk.java.net/projects/code-tools/jmh/
JMH主要用于量化Java代码的性能,主要应用场景如下:
- 对于已知的函数进行进一步优化
- 确认函数执行时间以及于参数的关系