java中操作字符串的三种常见类String、StringBuffer、StringBuilder,string被final修饰,内容不可变,每次对String赋值都是new了一个新的对象,用"+"拼接也是new一个新对象。
而StringBuffer、StringBuilder提供了append方法,允许对象在原来的基础上直接添加字符串,StringBuilder是线程不安全的
package cn.itsource.stringbuffer;
public class StringBufferTest {
public static void main(String[] args) {
/*
* String 效率低
* StringBuffer 线程安全,效率比StringBuilder稍低
* StringBuilder 效率最高,线程不安全
* */
String str = "ABC";
char charAt = str.charAt(2);//得到索引位置的字符
System.out.println(charAt);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("1994").append("true").append("50kg");
System.out.println(stringBuffer);
System.out.println("===============");
/*
* 验证三种方式处理字符串的效率(ms)
* 1K 10K 100K 1000K
* String 4 195 16774
* StringBuffer 1 2 22 73
* StringBuilder 1 2 18 62
* */
/*
* String
*
long start = System.currentTimeMillis();
String s = "";
for (int i = 0; i < 100000; i++) {
s+=i;
}
long end = System.currentTimeMillis();
System.out.println(end-start);*/
/*
* StringBuffer
*/
/*long start = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000000; i++) {
sb.append(i);
}
long end = System.currentTimeMillis();
System.out.println(end-start);*/
long start = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000000; i++) {
sb.append(i);
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
}