为什么使用 StringBuilder?StringBuffer 可以与多个线程以及一个线程一起使用吗?
假设我们的应用程序只有一个线程.而我们正在使用 StringBuffer
那么有什么问题呢?
Suppose our application have only one thread. and we are using StringBuffer
then what is the problem?
我的意思是如果StringBuffer
可以通过同步处理多个线程,那么单线程工作有什么问题?
I mean if StringBuffer
can handle multiple threads through synchronization, what is the problem to work with single thread?
为什么要改用 StringBuilder
?
推荐答案
StringBuffers
是线程安全的,意味着它们有同步的方法来控制访问,因此只有一个线程可以访问 StringBuffer 对象的同步一次编码.因此,StringBuffer 对象通常可以安全地用于多线程环境中,其中多个线程可能试图同时访问同一个 StringBuffer 对象.
StringBuffers
are thread-safe, meaning that they have synchronized methods to control access so that only one thread can access a StringBuffer object's synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.
StringBuilder 的
访问不同步,因此它不是线程安全的.通过不同步,StringBuilder 的性能可以优于 StringBuffer.因此,如果您在单线程环境中工作,使用 StringBuilder 而不是 StringBuffer 可能会提高性能.这也适用于其他情况,例如只有一个线程将访问 StringBuilder 对象的 StringBuilder 局部变量(即方法中的变量).
StringBuilder's
access is not synchronized so that it is not thread-safe. By not being synchronized, the performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance. This is also true of other situations such as a StringBuilder local variable (ie, a variable within a method) where only one thread will be accessing a StringBuilder object.
所以,更喜欢 StringBuilder
因为,
So, prefer StringBuilder
because,
- 性能提升小.
- StringBuilder 是 StringBuffer 类的 1:1 替代品.
- StringBuilder 不是线程同步的,因此在大多数 Java 实现上表现更好
看看这个:
- 不要使用StringBuffer!
- StringBuffer 与 StringBuilder 性能比较
相关文章