字符串拼接

古城微笑少年丶 2021-09-22 23:10 764阅读 0赞
  1. public class K {
  2. public static void main(String[] args) {
  3. //+
  4. long start_01 = System.currentTimeMillis();
  5. String a = "a";
  6. for(int i = 0 ; i < 100000 ; i++){
  7. a += "b";
  8. }
  9. long end_01 = System.currentTimeMillis();
  10. System.out.println(" + 所消耗的时间:" + (end_01 - start_01) + "ms");
  11. //concat
  12. long start_02 = System.currentTimeMillis();
  13. String c = "c";
  14. for(int i = 0 ; i < 100000 ; i++){
  15. c = c.concat("d");
  16. }
  17. long end_02 = System.currentTimeMillis();
  18. System.out.println("concat所消耗的时间:" + (end_02 - start_02) + "ms");
  19. //append
  20. long start_03 = System.currentTimeMillis();
  21. StringBuffer e = new StringBuffer("e");
  22. for(int i = 0 ; i < 100000 ; i++){
  23. e.append("d");
  24. }
  25. long end_03 = System.currentTimeMillis();
  26. System.out.println("append所消耗的时间:" + (end_03 - start_03) + "ms");
  27. }
  28. }
  29. Output
  30. + 所消耗的时间:1796ms
  31. concat所消耗的时间:655ms
  32. append所消耗的时间:10ms

+方式拼接字符串


编译器对+进行优化,使其使用StringBuilder的append()方法处理字符串。我们知道StringBuilder的速度比StringBuffer的速度更加快,但是为何运行速度还是那样呢?主要是因为编译器使用append()方法追加后要用toString()转换成String字符串,也就说 str +=”b”等同于str = new StringBuilder(str).append(“b”).toString();它变慢的关键原因就在于new StringBuilder()和toString()。

concat()方法拼接字符串


  1. public String concat(String str) {
  2. int olen = str.length();
  3. if (olen == 0) {
  4. return this;
  5. }
  6. if (coder() == str.coder()) {
  7. byte[] val = this.value;
  8. byte[] oval = str.value;
  9. int len = val.length + oval.length;
  10. byte[] buf = Arrays.copyOf(val, len);
  11. System.arraycopy(oval, 0, buf, val.length, oval.length);
  12. return new String(buf, coder);
  13. }
  14. int len = length();
  15. byte[] buf = StringUTF16.newBytesFor(len + olen);
  16. getBytes(buf, 0, UTF16);
  17. str.getBytes(buf, len, UTF16);
  18. return new String(buf, UTF16);
  19. }

这是concat()的源码,尽管有数组的拷贝,但仍然返回new String();创建了10W个字符串对象,这是它变慢的根本原因。

append()方法拼接字符串


  1. public synchronized StringBuffer append(String str) {
  2. toStringCache = null;
  3. super.append(str);
  4. return this;
  5. }
  6. public AbstractStringBuilder append(String str) {
  7. if (str == null) {
  8. return appendNull();
  9. }
  10. int len = str.length();
  11. ensureCapacityInternal(count + len);
  12. putStringAt(count, str);
  13. count += len;
  14. return this;
  15. }

append()方法返回的是本身,也就说在整个10W次的循环过程中,并没有产生新的字符串对象。

发表评论

表情:
评论列表 (有 0 条评论,764人围观)

还没有评论,来说两句吧...

相关阅读

    相关 字符串拼接

    最近在研究《javascript高级程序设计》中,有一段关于字符串特点的描述,原文大概如下:ECMAScript中的字符串是不可变的,也就是说,字符串一旦创建,他们的值就不能改