--1,概述
用来优化字符串拼接效率的工具类
--2,创建对象
StringBuffer()
构造一个其中不带字符的字符串缓冲区,其初始容量为 16 个字符。
--3,常用方法
StringBuffer append(String str)
将指定的字符串追加到此字符序列。
--4,测试
package cn.tedu.api;
//测试 字符串拼接工具类
public class Test3_StringBuffer {
public static void main(String[] args) {
// method();//用+拼接
method2();//用工具类拼接
}
public static void method2() {
String s = "abcdefg" ;
// StringBuilder sb = new StringBuilder();
StringBuffer sb = new StringBuffer();
long start = System.currentTimeMillis() ;//计时开始
for (int i = 0; i < 100000; i++) {
sb.append(s);//利用工具追加数据
}
long end = System.currentTimeMillis() ;//计时结束
System.out.println(end-start);//9ms
}
public static void method() {
String s = "abcdefg" ;
String res = "" ;//定义变量,记录拼接结果
long start = System.currentTimeMillis() ;//计时开始
for (int i = 0; i < 100000; i++) {
res = res + s ;//通过+拼接字符串
}
long end = System.currentTimeMillis() ;//计时结束
System.out.println(end-start);//50277ms
}
}原文:https://www.cnblogs.com/liang-shi/p/13849962.html