为什么要使用StringBuilder? StringBuffer可以使用多个线程以及一个线程吗? [英] Why use StringBuilder? StringBuffer can work with multiple thread as well as one thread?
问题描述
假设我们的应用程序只有一个线程。我们正在使用 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
因为,
- 小的性能提升。
- StringBuilder是StringBuffer类的1:1替代品。
- StringBuilder不是线程同步的,因此在大多数Java实现上表现更好
检查这个out:
- Don't Use StringBuffer!
- StringBuffer vs. StringBuilder performance comparison
这篇关于为什么要使用StringBuilder? StringBuffer可以使用多个线程以及一个线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!