java8字符串分隔符拼接
最近在做需求时偶然发现java8的String多了几个新方法,其中有个String.join是做字符串分隔符拼接的
执行时间测试
我们平时在做字符串拼接时,一般字符串数量少时用String,多时用StringBuilder,基本都是形如
StringBuilder sb1 = new StringBuilder();
for (String s: strings) {
if(sb.length() == 0 ) {
sb1.append(s);
} else {
sb1.append(",").append(s);
}
}
的用法,而java8提供了一个String.join(CharSequence delimiter,
Iterable<? extends CharSequence> elements),我们先测试下各种写法的时耗
List<String> strings = Arrays.asList(......);
long l1 = System.currentTimeMillis();
String join = String.join(",", strings);
long l2 = System.currentTimeMillis();
System.err.println("java8String分隔符分隔耗时: " + (l2 -l1));
long l3 = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (CharSequence cs: strings) {
if(sb.length() == 0 ) {
sb.append(cs);
} else {
sb.append(",").append(cs);
}
}
long l4 = System.currentTimeMillis();
System.err.println("StringBuilder分隔符拼接(CharSequence)耗时: " + (l4 -l3));
long l5 = System.currentTimeMillis();
StringBuilder sb1 = new StringBuilder();
for (String s: strings) {
if(sb.length() == 0 ) {
sb1.append(s);
} else {
sb1.append(",").append(s);
}
}
long l6 = System.currentTimeMillis();
System.err.println("StringBuilder分隔符拼接(String)耗时: " + (l6 -l5));
long l7 = System.currentTimeMillis();
String str = "";
for (String e : strings) {
str += (e + ",");
}
str = str.substring(0, str.length() - 1);
long l8 = System.currentTimeMillis();
System.err.println("String分隔符拼接耗时: " + (l8 -l7));
list长度: 4050
java8String分隔符分隔耗时: 2
StringBuilder分隔符拼接(CharSequence)耗时: 15
StringBuilder分隔符拼接(String)耗时: 1
String分隔符拼接耗时: 222
可以看到前三种耗时基本一样,而字符串量很大的情况下,第四种耗时激增,再来看下join的源码
public static String join(CharSequence delimiter,
Iterable<? extends CharSequence> elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: elements) {
joiner.add(cs);
}
return joiner.toString();
}
// 在StringJoiner.add中,可以看到是也是调用了StringBuilder
private StringBuilder prepareBuilder() {
if (value != null) {
value.append(delimiter);
} else {
value = new StringBuilder().append(prefix);
}
return value;
}
public StringJoiner add(CharSequence newElement) {
prepareBuilder().append(newElement);
return this;
}
底层写法其实和我们自己写的逻辑是一样的,所以说,采纳哪种写法都行,而采用String.join()更“优雅” 😊