所在包
java.lang
区别总结
String对象不可变验证(面试)
@Test
public void test1(){
String str = "str, hello";
StringBuilder sb = new StringBuilder(str);
this.change(str, sb);
System.out.println("change后,str = " + str);
System.out.println("change后,sb = " + sb);
}
public void change(String str, StringBuilder sb){
str += "world";
sb.append("world");
System.out.println("change方法中,str = " + str);
System.out.println("change方法中,sb = " + sb);
System.out.println("");
}
/*
打印结果:
change方法中,str = str, helloworld
change方法中,sb = str, helloworld
change后,str = str, hello
change后,sb = str, helloworld
*/
StringBuilder、StringBuffer详解
拼接字符的 效率 及 占用内存 验证
结论
注:在单线程情况下验证 效率: StringBuilder > StringBuffer > String
内存占用:StringBuilder = StringBuffer < String
代码验证
public static void main(String[] args) {
testString();
// testStringBuilder();
// testStringBuffer();
}
public static void testString(){
String str = "";
long s1 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
str += i;
}
System.out.println(str);
long e1 = System.currentTimeMillis();
long useMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("String用时(毫秒):" + (e1 - s1) + ", 占用内存(字节):" + useMemory);
}
public static void testStringBuilder(){
long s2 = System.currentTimeMillis();
StringBuilder sbuil = new StringBuilder();
System.out.println(sbuil);
for (int i = 0; i < 100000; i++) {
sbuil.append(i);
}
long e2 = System.currentTimeMillis();
long useMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("StringBuilder用时(毫秒):" + (e2 - s2) + ", 占用内存(字节):" + useMemory);
}
public static void testStringBuffer(){
long s3 = System.currentTimeMillis();
StringBuffer sbuff = new StringBuffer();
System.out.println(sbuff);
for (int i = 0; i < 100000; i++) {
sbuff.append(i);
}
long e3 = System.currentTimeMillis();
long useMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("StringBuffer 用时(毫秒):" + (e3 - s3) + ", 占用内存(字节):" + useMemory);
}
/*
结果(每次结果有差异):
String用时(毫秒):36575, 占用内存(字节):463297536
StringBuilder用时(毫秒):19, 占用内存(字节):12519168
StringBuffer 用时(毫秒):34, 占用内存(字节):12519168
*/