请告诉我一个实时情况比较字符串,StringBuffer,和StringBuilder?
当前回答
字符串
String类表示字符串。Java程序中的所有字符串字面值,例如“abc”,都被实现为该类的实例。
字符串对象是不可变的,一旦创建就不能改变。(字符串是常量)
If a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPool. But before saving in pool it invokes intern() method to check object availability with same content in pool using equals method. If String-copy is available in the Pool then returns the reference. Otherwise, String object is added to the pool and returns the reference. The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String heapSCP = new String("Yash"); heapSCP.concat("."); heapSCP = heapSCP + "M"; heapSCP = heapSCP + 777; // For Example: String Source Code public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); } String literals are stored in StringConstantPool. String onlyPool = "Yash";
StringBuilder和StringBuffer是可变的字符序列。这意味着可以改变这些对象的值。StringBuffer具有与StringBuilder相同的方法,但是StringBuffer中的每个方法都是同步的,因此它是线程安全的。
StringBuffer and StringBuilder data can only be created using new operator. So, they get stored in Heap memory. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. StringBuffer threadSafe = new StringBuffer("Yash"); threadSafe.append(".M"); threadSafe.toString(); StringBuilder nonSync = new StringBuilder("Yash"); nonSync.append(".M"); nonSync.toString(); StringBuffer and StringBuilder are having a Special methods like., replace(int start, int end, String str) and reverse(). NOTE: StringBuffer and SringBuilder are mutable as they provides the implementation of Appendable Interface.
什么时候用哪一个。
If a you are not going to change the value every time then its better to Use String Class. As part of Generics if you want to Sort Comparable<T> or compare a values then go for String Class. //ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable Set<StringBuffer> set = new TreeSet<StringBuffer>(); set.add( threadSafe ); System.out.println("Set : "+ set); If you are going to modify the value every time the go for StringBuilder which is faster than StringBuffer. If multiple threads are modifying the value the go for StringBuffer.
其他回答
可变性的区别:
String是不可变的,如果你试图改变它们的值,就会创建另一个对象,而StringBuffer和StringBuilder是可变的,所以它们可以改变它们的值。
线程安全的区别:
StringBuffer和StringBuilder的区别在于StringBuffer是线程安全的。因此,当应用程序只需要在一个线程中运行时,最好使用StringBuilder。StringBuilder比StringBuffer更有效。
情况:
如果你的字符串不会改变,请使用string类,因为string对象是不可变的。 如果您的字符串可以更改(例如:字符串构造中的大量逻辑和操作),并且只能从单个线程访问,那么使用StringBuilder就足够了。 如果您的字符串可以更改,并且可以从多个线程访问,请使用StringBuffer,因为StringBuffer是同步的,因此具有线程安全性。
In java, String is immutable. Being immutable we mean that once a String is created, we can not change its value. StringBuffer is mutable. Once a StringBuffer object is created, we just append the content to the value of object instead of creating a new object. StringBuilder is similar to StringBuffer but it is not thread-safe. Methods of StingBuilder are not synchronized but in comparison to other Strings, the Stringbuilder runs fastest. You can learn difference between String, StringBuilder and StringBuffer by implementing them.
You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated). You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together. You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).
这里有一个例子。
基础知识:
String是一个不可变的类,它不能被改变。 StringBuilder是一个可变类,可以追加,字符替换或删除,并最终转换为String StringBuffer是StringBuilder的原始同步版本
在只有一个线程访问对象的所有情况下,您都应该使用StringBuilder。
细节:
还要注意,StringBuilder/Buffers并不是魔法,它们只是使用一个数组作为支持对象,当数组满时必须重新分配。确保在初始时创建足够大的StringBuilder/Buffer对象,这样就不必在每次调用.append()时不断地调整它们的大小。
调整大小会变得非常糟糕。基本上,每次需要扩展时,它都会将支持数组的大小调整为当前大小的2倍。这可能导致在StringBuilder/Buffer类开始变大时分配大量RAM而不使用。
In Java String x = "A" + "B"; uses a StringBuilder behind the scenes. So for simple cases there is no benefit of declaring your own. But if you are building String objects that are large, say less than 4k, then declaring StringBuilder sb = StringBuilder(4096); is much more efficient than concatenation or using the default constructor which is only 16 characters. If your String is going to be less than 10k then initialize it with the constructor to 10k to be safe. But if it is initialize to 10k then you write 1 character more than 10k, it will get re-allocated and copied to a 20k array. So initializing high is better than to low.
在自动调整大小的情况下,在第17个字符时,后面的数组被重新分配并复制为32个字符,在第33个字符时,同样发生这种情况,你需要重新分配并将数组复制为64个字符。你可以看到这是如何退化为大量的重新分配和复制,这是你真正试图避免使用StringBuilder/Buffer在第一个地方。
这是来自JDK 6的AbstractStringBuilder源代码
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
一个最好的做法是初始化StringBuilder/Buffer,如果你不知道String会有多大,但你可以猜测,比你认为你需要的要大一点。分配比您需要的稍微多一点的内存比大量的重新分配和复制要好。
另外,要注意用String初始化StringBuilder/Buffer,因为这样只会分配String + 16个字符的大小,在大多数情况下,这只会开始退化的重新分配和复制周期,而这是您试图避免的。下面是直接来自Java 6的源代码。
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
如果碰巧得到了一个不是自己创建的StringBuilder/Buffer实例,并且不能控制所调用的构造函数,有一种方法可以避免恶化的重新分配和复制行为。调用. ensurecapacity(),并设置你想要确保生成的字符串适合的大小。
的选择:
需要注意的是,如果您正在进行非常繁重的字符串构建和操作,有一种更面向性能的替代方法,称为rope。
另一种替代方法是通过子类化ArrayList<String>来创建一个StringList实现,并添加计数器来跟踪每个.append()和列表的其他突变操作上的字符数,然后重写. tostring()来创建一个你需要的精确大小的StringBuilder,并循环遍历列表并构建输出,你甚至可以使该StringBuilder成为一个实例变量并“缓存”. tostring()的结果,只有在发生变化时才需要重新生成它。
在构建固定格式化输出时也不要忘记String.format(),编译器可以优化它,因为它们使它更好。
字符串
String类表示字符串。Java程序中的所有字符串字面值,例如“abc”,都被实现为该类的实例。
字符串对象是不可变的,一旦创建就不能改变。(字符串是常量)
If a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPool. But before saving in pool it invokes intern() method to check object availability with same content in pool using equals method. If String-copy is available in the Pool then returns the reference. Otherwise, String object is added to the pool and returns the reference. The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String heapSCP = new String("Yash"); heapSCP.concat("."); heapSCP = heapSCP + "M"; heapSCP = heapSCP + 777; // For Example: String Source Code public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); } String literals are stored in StringConstantPool. String onlyPool = "Yash";
StringBuilder和StringBuffer是可变的字符序列。这意味着可以改变这些对象的值。StringBuffer具有与StringBuilder相同的方法,但是StringBuffer中的每个方法都是同步的,因此它是线程安全的。
StringBuffer and StringBuilder data can only be created using new operator. So, they get stored in Heap memory. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. StringBuffer threadSafe = new StringBuffer("Yash"); threadSafe.append(".M"); threadSafe.toString(); StringBuilder nonSync = new StringBuilder("Yash"); nonSync.append(".M"); nonSync.toString(); StringBuffer and StringBuilder are having a Special methods like., replace(int start, int end, String str) and reverse(). NOTE: StringBuffer and SringBuilder are mutable as they provides the implementation of Appendable Interface.
什么时候用哪一个。
If a you are not going to change the value every time then its better to Use String Class. As part of Generics if you want to Sort Comparable<T> or compare a values then go for String Class. //ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable Set<StringBuffer> set = new TreeSet<StringBuffer>(); set.add( threadSafe ); System.out.println("Set : "+ set); If you are going to modify the value every time the go for StringBuilder which is faster than StringBuffer. If multiple threads are modifying the value the go for StringBuffer.
推荐文章
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我可以将c#字符串值转换为转义字符串文字吗?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 在c#中解析字符串为日期时间
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 字符串中的单词大写
- 如何在方法中访问“静态”类变量?
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?