String,StringBuffer,StringBuilder比较
程序员文章站
2022-06-07 17:14:19
...
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更高。
上一篇: 青檬怎么吃最合适?告诉你几种吃法
推荐阅读
-
Java之String、StringBuffer、StringBuilder的区别分析
-
浅析C#中StringBuilder类的高效及与String的对比
-
String、StringBuffer和StringBuilder类的区别
-
java中String和StringBuffer的区别
-
全面解释java中StringBuilder、StringBuffer、String类之间的关系
-
详解.NET中string与StringBuilder在字符串拼接功能上的比较
-
Java中String、StringBuffer、StringBuilder的区别(转)
-
C#中String StringBuilder StringBuffer类的用法
-
ASP.NET(C#) String, StringBuilder 与 StringWriter性能比较
-
StringBuilder、StringBuffer分析比较