欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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线程安全的
/**
 * 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更高。