刚学java的时候拼接字符串一直都是使用“+”进行拼接,感觉用起来简单又方便,后来又了解到拼接字符串的另一个方法,String.format()。特此记录下来学习一下;
在拼接字符串时我们通常会有两种方法,一种是用String
类重载‘+’运算符进行拼接,其实是用StringBuilder.append
。还有一种类似C的printf
风格,调用String.format()
,底层是调用formatter.format
方法。那从性能和内存占用两个方面考虑到底是哪一个方法更好呢?
class StringTest {
public static void main(String[] args) {
// testOperatorPlus();
//testAppend();
testFormat();
}
private static void testFormat() {
Runtime runtime = Runtime.getRuntime();
long memory;
long prev_time;
int i;
long time;
StringBuilder sb = new StringBuilder();
memory = runtime.freeMemory();
prev_time = System.currentTimeMillis();
for (i = 0; i < 10000; i++) {
String s = String.format("Blah %d Blah %d Blah %d", i, i, i);
}
long ww=runtime.freeMemory();
time = System.currentTimeMillis() - prev_time;
memory = memory - ww;
System.out.println("Time: " + time + " Memory Usage: " + memory);
}
private static void testAppend() {
Runtime runtime = Runtime.getRuntime();
long memory;
long prev_time;
int i;
long time;
StringBuilder sb = new StringBuilder();
memory = runtime.freeMemory();
prev_time = System.currentTimeMillis();
for (i = 0; i < 10000; i++) {
sb.append("Blah ");
sb.append(i);
sb.append("Blah ");
sb.append(i);
sb.append("Blah ");
sb.append(i);
}
time = System.currentTimeMillis() - prev_time;
memory = memory - runtime.freeMemory();
System.out.println("Time: " + time + " Memory Usage: " + memory);
}
private static void testOperatorPlus() {
Runtime runtime = Runtime.getRuntime();
long memory;
long prev_time;
int i;
long time;
StringBuilder sb = new StringBuilder();
memory = runtime.freeMemory();
prev_time = System.currentTimeMillis();
for (i = 0; i < 1000000; i++) {
String s = "Blah " + i + "Blah " + i + "Blah " + i;
}
time = System.currentTimeMillis() - prev_time;
memory = memory - runtime.freeMemory();
System.out.println("Time: " + time + " Memory Usage: " + memory);
}
}
结果如下:
可以看到StringBuilder.append
的执行时间和内存占用都是最优的。'+'运算符比直接调用StringBuilder.append
要慢上不少,特别是要连接的字符串数量较多时,内存占用也特别大。String.format
由于每次都有生成一个Formatter
对象,较慢也是情理之中。
format常用的字符和整数类型的格式化如下:
转换符 | 详细说明 | 示例 |
---|---|---|
%s | 字符串类型 | “喜欢请收藏” |
%c | 字符类型 | ‘m’ |
%b | 布尔类型 | true |
%d | 整数类型(十进制) | 88 |
%x | 整数类型(十六进制) | FF |
%o | 整数类型(八进制) | 77 |
%f | 浮点类型 | 8.888 |
%a | 十六进制浮点类型 | FF.35AE |
%e | 指数类型 | 9.38e+5 |
%g | 通用浮点类型(f和e类型中较短的) | 不举例(基本用不到) |
%h | 散列码 | 不举例(基本用不到) |
%% | 百分比类型 | %(%特殊字符%%才能显示%) |
%n | 换行符 | 不举例(基本用不到) |
%tx | 日期与时间类型(x代表不同的日期与时间转换符) | 不举例(基本用不到) |