所在包

java.lang

区别总结

image.png

String对象不可变验证(面试)

  1. @Test
  2. public void test1(){
  3. String str = "str, hello";
  4. StringBuilder sb = new StringBuilder(str);
  5. this.change(str, sb);
  6. System.out.println("change后,str = " + str);
  7. System.out.println("change后,sb = " + sb);
  8. }
  9. public void change(String str, StringBuilder sb){
  10. str += "world";
  11. sb.append("world");
  12. System.out.println("change方法中,str = " + str);
  13. System.out.println("change方法中,sb = " + sb);
  14. System.out.println("");
  15. }
  16. /*
  17. 打印结果:
  18. change方法中,str = str, helloworld
  19. change方法中,sb = str, helloworld
  20. change后,str = str, hello
  21. change后,sb = str, helloworld
  22. */

**

StringBuilder、StringBuffer详解

image.png

拼接字符的 效率 及 占用内存 验证

结论

注:在单线程情况下验证 效率StringBuilder > StringBuffer > String

内存占用StringBuilder = StringBuffer < String

代码验证

  1. public static void main(String[] args) {
  2. testString();
  3. // testStringBuilder();
  4. // testStringBuffer();
  5. }
  6. public static void testString(){
  7. String str = "";
  8. long s1 = System.currentTimeMillis();
  9. for (int i = 0; i < 100000; i++) {
  10. str += i;
  11. }
  12. System.out.println(str);
  13. long e1 = System.currentTimeMillis();
  14. long useMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
  15. System.out.println("String用时(毫秒):" + (e1 - s1) + ", 占用内存(字节):" + useMemory);
  16. }
  17. public static void testStringBuilder(){
  18. long s2 = System.currentTimeMillis();
  19. StringBuilder sbuil = new StringBuilder();
  20. System.out.println(sbuil);
  21. for (int i = 0; i < 100000; i++) {
  22. sbuil.append(i);
  23. }
  24. long e2 = System.currentTimeMillis();
  25. long useMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
  26. System.out.println("StringBuilder用时(毫秒):" + (e2 - s2) + ", 占用内存(字节):" + useMemory);
  27. }
  28. public static void testStringBuffer(){
  29. long s3 = System.currentTimeMillis();
  30. StringBuffer sbuff = new StringBuffer();
  31. System.out.println(sbuff);
  32. for (int i = 0; i < 100000; i++) {
  33. sbuff.append(i);
  34. }
  35. long e3 = System.currentTimeMillis();
  36. long useMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
  37. System.out.println("StringBuffer 用时(毫秒):" + (e3 - s3) + ", 占用内存(字节):" + useMemory);
  38. }
  39. /*
  40. 结果(每次结果有差异):
  41. String用时(毫秒):36575, 占用内存(字节):463297536
  42. StringBuilder用时(毫秒):19, 占用内存(字节):12519168
  43. StringBuffer 用时(毫秒):34, 占用内存(字节):12519168
  44. */