为什么 StringBuilder 比 String 快得多? [英] Why is StringBuilder much faster than String?

查看:47
本文介绍了为什么 StringBuilder 比 String 快得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 StringBuilder 比使用 + 运算符进行字符串连接要快得多?尽管 + 运算符在内部是使用 StringBufferStringBuilder 实现的.

Why is StringBuilder much faster than string concatenation using the + operator? Even though that the + operator internally is implemented using either StringBuffer or StringBuilder.

public void shortConcatenation(){
    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTime <= 1000){

        character += "Y";
    }

    System.out.println("short: " + character.length());
}

////使用字符串构建器

//// using String builder

 public void shortConcatenation2(){
    long startTime = System.currentTimeMillis();
    StringBuilder sb = new StringBuilder();
    while (System.currentTimeMillis() - startTime <= 1000){

        sb.append("Y");
    }
    System.out.println("string builder short: " + sb.length());
}

我知道这里有很多类似的问题,但这些都没有真正回答我的问题.

推荐答案

你了解它内部是如何工作的吗?

Do you understand how it works internally?

每次执行 stringA += stringB; 都会创建一个新字符串并分配给 stringA,因此它会消耗内存(一个新的字符串实例!)和时间(复制旧字符串 + 新字符串)另一个字符串的字符).

Every time you do stringA += stringB; a new string is created an assigned to stringA, so it will consume memory (a new string instance!) and time (copy the old string + new characters of the other string).

StringBuilder 将在内部使用字符数组,当您使用 .append() 方法时,它会做几件事:

StringBuilder will use an array of characters internally and when you use the .append() method it will do several things:

  • 检查是否有任何可用空间供字符串追加
  • 再次进行一些内部检查并运行 System.arraycopy 以复制数组中字符串的字符.
  • check if there are any free space for the string to append
  • again some internal checks and run a System.arraycopy to copy the characters of the string in the array.

就个人而言,我认为每次分配一个新字符串(创建字符串的新实例,放置字符串等)在内存和速度方面可能会非常广泛(在 while/for 等,尤其是).

Personally, I think the allocation of a new string every time (creating a new instance of string, put the string, etc.) could be very expansive in terms of memory and speed (in while/for, etc. especially).

在您的示例中,使用 StringBuilder 更好,但是如果您需要(示例)像 .toString() 这样简单的东西,

In your example, use a StringBuilder is better, but if you need (example) something simple like a .toString(),

public String toString() {
    return StringA + " - " + StringB;
}

没有区别(嗯,在这种情况下,最好避免 StringBuilder 开销,这在这里没用).

makes no differences (well, in this case it is better you avoid StringBuilder overhead which is useless here).

这篇关于为什么 StringBuilder 比 String 快得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆