字符串的替换操作我们通常用String类的replace方法,但是java1.9之前版本的replace方法性能表现不是很理想的,可以采用
org.apache.commons.lang3.StringUtils
代替String类的replace方法,通过如下代码测试进行测试
public class TestReplace {
public static void main(String[] args) {
String str = "hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world";
LocalDateTime t1 = LocalDateTime.now();
for(int i = 0; i < 10000; i++) {
str.replace("hello", "hi");
}
System.out.println(Duration.between(t1, LocalDateTime.now()).toMillis());
t1=LocalDateTime.now();
for(int i = 0; i < 10000; i++) {
StringUtils.replace(str,"hello", "hi");
}
System.out.println(Duration.between(t1, LocalDateTime.now()).toMillis());
}
}
//三次运行结果
82
37
------
104
41
------
128
62
测试结果显示高并发场景下,StringUtils的replace方法的性能是String.replace方法的两倍以上。
网友评论