String,StringBuffer,StringBuilder比较
程序员文章站
2022-06-07 17:14:31
...
String,StringBuffer,StringBuilder这三个类都实现了同样的接口,java.io.Serializable, Comparable<String>, CharSequence也就是说他们大概的功能都是相同的,但是因为某些微小的变化导致了他们存在一些功能的差异。
首先:String一旦new出来值将不会改变,
JDK分析
private final char value[];
StringBuffer,StringBuilder的值都是可以改变的,
char value[];
第二:StringBuffer,StringBuilder性能差异
StringBuffer线程安全的
而StringBuilder却不是的,
综合而言,String的值无法改变,StringBuffer,StringBuilder可以,但是StringBuilder的性能比
StringBuffer更高。
首先:String一旦new出来值将不会改变,
JDK分析
private final char value[];
StringBuffer,StringBuilder的值都是可以改变的,
char value[];
第二:StringBuffer,StringBuilder性能差异
StringBuffer线程安全的
/** * A thread-safe, mutable sequence of characters. * A string buffer is like a {@link String}, but can be modified. At any * point in time it contains some particular sequence of characters, but * the length and content of the sequence can be changed through certain * method calls. * <p> * String buffers are safe for use by multiple threads. The methods * are synchronized where necessary so that all the operations on any * particular instance behave as if they occur in some serial order * that is consistent with the order of the method calls made by each of * the individual threads involved. * <p> * The principal operations on a <code>StringBuffer</code> are the * <code>append</code> and <code>insert</code> methods, which are * overloaded so as to accept data of any type. Each effectively * converts a given datum to a string and then appends or inserts the * characters of that string to the string buffer. The * <code>append</code> method always adds these characters at the end * of the buffer; the <code>insert</code> method adds the characters at * a specified point. * <p>
而StringBuilder却不是的,
/** * A mutable sequence of characters. This class provides an API compatible * with <code>StringBuffer</code>, but with no guarantee of synchronization. * This class is designed for use as a drop-in replacement for * <code>StringBuffer</code> in places where the string buffer was being * used by a single thread (as is generally the case). Where possible, * it is recommended that this class be used in preference to * <code>StringBuffer</code> as it will be faster under most implementations. *
综合而言,String的值无法改变,StringBuffer,StringBuilder可以,但是StringBuilder的性能比
StringBuffer更高。
推荐阅读
-
C#中String和StringBuilder的简介与区别
-
C#使用String和StringBuilder运行速度测试及各自常用方法简介
-
全面解释java中StringBuilder、StringBuffer、String类之间的关系
-
C#中StringBuilder用法以及和String的区别分析
-
浅析Java中String与StringBuffer拼接的区别
-
java中String与StringBuilder的区别
-
C#中String StringBuilder StringBuffer类的用法
-
string与stringbuilder两者的区别
-
java_String和StringBuffer区别分析
-
Java之String、StringBuffer、StringBuilder的区别分析