一、 执行速度:
1、三者在执行速度方面的比较:StringBuilder > StringBuffer > String
String:字符串常量
StringBuffer:字符串变量
StringBuilder:字符串变量
String是字符串常量,是不可改变的对象。
import org.junit.Test;
public class StringBufferWithStringBuilder {
public void testString() {
long start = System.currentTimeMillis();
String str = null;
for (int i = 0; i < 20000; i++) {
str = str + i + ",";
}
System.out.println(System.currentTimeMillis() - start);
}
public void testStringBuffer() {
long start = System.currentTimeMillis();
StringBuffer sbuf = new StringBuffer();
for (int i = 0; i < 20000; i++) {
sbuf.append(i + ",");
}
System.out.println(System.currentTimeMillis() - start);
}
public void testStringBulider() {
long start = System.currentTimeMillis();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 20000; i++) {
builder.append(i + ",");
}
System.out.println(System.currentTimeMillis() - start);
}
@Test
public void test(){
testString();
testStringBuffer();
testStringBulider();
}
}
执行结果:
1217
9
6
二、StringBuffer常用方法:
StringBuffer s = new StringBuffer();
这样初始化出的StringBuffer对象是一个空的对象,
StringBuffersb1=new StringBuffer(512);
分配了长度512字节的字符缓冲区
方便用于字符串的连接
StringBuffer newsql = new StringBuffer("select count(*) from material,warehouse ") ;
StringBuilder whereSql = new StringBuilder("where material.warehouse_id=warehouse.warehouse_id and material.del=0 ");
List<Object> params = new ArrayList<Object>();
String material_id = material.getMaterial_id();
if(material_id != null && !material_id.trim().isEmpty()) {
whereSql.append("and material_id=? ");
params.add(material_id);
}
String material_name = material.getMaterial_name();
if(material_name != null && !material_name.trim().isEmpty()){
whereSql.append("and material_name=? ");
params.add( material_name);
}
Long num =null;
try {
num = (long) tr.query(newsql.append(whereSql).toString(), new ScalarHandler(),params.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
三、Append:
1、 public StringBuffer append(boolean b)
该方法的作用是追加内容到当前StringBuffer对象的末尾,类似于字符串的连接,调用该方法以后,StringBuffer对象的内容也发生改 变,例如:
StringBuffer sb = new StringBuffer(“abc”);
sb.append(true);
则对象sb的值将变成”abctrue”
2、 使用该方法进行字符串的连接,将比String更加节约内容,经常应用于数据库SQL语句的连接