StringBuffer和StringBuilder区别?
1. String是不可变类,改变String变量中的值,相当于开辟了新的空间存放新的string变量
2. StringBuffer 可变的类,可以通过append方法改变变量的值,且StringBuffer是线程安全的,它的很多方法都是同步方法,支持并发操作,适用于多线程
3. StringBuilder 可变的类,但是线程不安全的,用于单线程中性能高于StringBuffer
4. HashTable 线程安全的,HashMap线程不安全的
为什么StringBuffer是同步的?
因为很多方法都是synchronized 。。。
/*
* @(#)StringBuffer.java 1.101 05/11/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/ package java.lang; /**
* 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>
* For example, if <code>z</code> refers to a string buffer object
* whose current contents are "<code>start</code>", then
* the method call <code>z.append("le")</code> would cause the string
* buffer to contain "<code>startle</code>", whereas
* <code>z.insert(4, "le")</code> would alter the string buffer to
* contain "<code>starlet</code>".
* <p>
* In general, if sb refers to an instance of a <code>StringBuffer</code>,
* then <code>sb.append(x)</code> has the same effect as
* <code>sb.insert(sb.length(), x)</code>.
* <p>
* Whenever an operation occurs involving a source sequence (such as
* appending or inserting from a source sequence) this class synchronizes
* only on the string buffer performing the operation, not on the source.
* <p>
* Every string buffer has a capacity. As long as the length of the
* character sequence contained in the string buffer does not exceed
* the capacity, it is not necessary to allocate a new internal
* buffer array. If the internal buffer overflows, it is
* automatically made larger.
*
* As of release JDK 5, this class has been supplemented with an equivalent
* class designed for use by a single thread, {@link StringBuilder}. The
* <tt>StringBuilder</tt> class should generally be used in preference to
* this one, as it supports all of the same operations but it is faster, as
* it performs no synchronization.
*
* @author Arthur van Hoff
* @version 1.101, 11/17/05
* @see java.lang.StringBuilder
* @see java.lang.String
* @since JDK1.0
*/
public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{ /** use serialVersionUID from JDK 1.0.2 for interoperability */
static final long serialVersionUID = 3388685877147921107L; /**
* Constructs a string buffer with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuffer() {
super(16);
} /**
* Constructs a string buffer with no characters in it and
* the specified initial capacity.
*
* @param capacity the initial capacity.
* @exception NegativeArraySizeException if the <code>capacity</code>
* argument is less than <code>0</code>.
*/
public StringBuffer(int capacity) {
super(capacity);
} /**
* Constructs a string buffer initialized to the contents of the
* specified string. The initial capacity of the string buffer is
* <code>16</code> plus the length of the string argument.
*
* @param str the initial contents of the buffer.
* @exception NullPointerException if <code>str</code> is <code>null</code>
*/
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
} /**
* Constructs a string buffer that contains the same characters
* as the specified <code>CharSequence</code>. The initial capacity of
* the string buffer is <code>16</code> plus the length of the
* <code>CharSequence</code> argument.
* <p>
* If the length of the specified <code>CharSequence</code> is
* less than or equal to zero, then an empty buffer of capacity
* <code>16</code> is returned.
*
* @param seq the sequence to copy.
* @exception NullPointerException if <code>seq</code> is <code>null</code>
* @since 1.5
*/
public StringBuffer(CharSequence seq) {
this(seq.length() + 16);
append(seq);
} public synchronized int length() {
return count;
} public synchronized int capacity() {
return value.length;
} ...
既然StringBuffer是线程同步的,那么代价就是损失性能,摘自一个测试http://blog.sina.com.cn/s/blog_5749ead90100b7lq.html
public class TestBufferAndBuilder {
public static void main(String[] args) {
String randoms[] = { String.valueOf(Math.random()), String.valueOf(Math.random()), String.valueOf(Math.random()), String.valueOf(Math.random()),
String.valueOf(Math.random()), String.valueOf(Math.random()), String.valueOf(Math.random()), String.valueOf(Math.random()), String.valueOf(Math.random()),
String.valueOf(Math.random()) };
System.gc();
long d = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuffer buffer = new StringBuffer();
buffer.append(randoms[0]).append(randoms[1]).append(randoms[2]).append(randoms[3]).append(randoms[4]).append(randoms[5]).append(randoms[6]).append(randoms[7]).append(
randoms[8]).append(randoms[9]);
}
System.err.println(System.currentTimeMillis() - d);
System.gc();
d = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuilder builder = new StringBuilder();
builder.append(randoms[0]).append(randoms[1]).append(randoms[2]).append(randoms[3]).append(randoms[4]).append(randoms[5]).append(randoms[6]).append(randoms[7]).append(
randoms[8]).append(randoms[9]);
}
System.err.println(System.currentTimeMillis() - d);
System.gc();
d = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuffer buffer = new StringBuffer(200);
buffer.append(randoms[0]).append(randoms[1]).append(randoms[2]).append(randoms[3]).append(randoms[4]).append(randoms[5]).append(randoms[6]).append(randoms[7]).append(
randoms[8]).append(randoms[9]);
}
System.err.println(System.currentTimeMillis() - d);
System.gc();
d = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuilder builder = new StringBuilder(200);
builder.append(randoms[0]).append(randoms[1]).append(randoms[2]).append(randoms[3]).append(randoms[4]).append(randoms[5]).append(randoms[6]).append(randoms[7]).append(
randoms[8]).append(randoms[9]);
}
System.err.println(System.currentTimeMillis() - d);
}
}
输出结果:
3188
3657
1672
1859
结果如上,基本上要慢10-20%
StringBuffer和StringBuilder区别?的更多相关文章
- String、StringBuffer、StringBuilder区别
String.StringBuffer.StringBuilder区别 StringBuffer.StringBuilder和String一样,也用来代表字符串.String类是不可变类,任何对Str ...
- String、StringBuffer和StringBuilder区别
String.StringBuffer和StringBuilder区别 1.长度是否可变 String 是被 final 修饰的,他的长度是不可变的,就算调用 String 的concat 方法,那也 ...
- 【37】String,StringBuffer,StringBuilder区别和概念
基本的概念: 查看 API 会发现,String.StringBuffer.StringBuilder 都实现了 CharSequence 接口,内部都是用一个char数组实现,虽然它们都与字符串相关 ...
- String、StringBuffer、StringBuilder区别并验证
© 版权声明:本文为博主原创文章,转载请注明出处 String.StringBuffer.StringBuilder的区别 1.String是一个常量,其对象一旦创建完毕就无法改变,当使用“+”拼接字 ...
- Java中的String、StringBuffer、StringBuilder区别以及Java之StringUtils的用法
1.String.StringBuffer.StringBuilder的区别 String是Java中基础类型,是immutable类(不可变)的典型实现,利用string进行拼接是会产生过多无用对象 ...
- Java中String、StringBuffer、StringBuilder区别与理解
一.先比较String.StringBuffer.StringBuilder变量的HashCode值 使用System.out.println(obj.hashcode())输出的时对象的哈希码, 而 ...
- String、StringBuffer和StringBuilder区别及性能分析
1.性能比较:StringBuilder > StringBuffer > String 2.String <(StringBuffer,StringBuilder)的原因 S ...
- String StringBuffer和StringBuilder区别及性能
结论: (1)如果要操作少量的数据用 String: (2)多线程操作字符串缓冲区下操作大量数据 StringBuffer: (3)单线程操作字符串缓冲区下操作大量数据 StringBuilder(推 ...
- stringbuffer 和 stringbuilder区别
stringbuffer 和 stringbuilder速度 小于 线程安全 线程非安全 单线程操作大量数据用stringbui ...
- String、StringBuffer与StringBuilder区别
1.三者在执行速度方面的比较:StringBuilder > StringBuffer > String 2.String <(StringBuffer,StringBuild ...
随机推荐
- POJ1056 IMMEDIATE DECODABILITY & POJ3630 Phone List
题目来源:http://poj.org/problem?id=1056 http://poj.org/problem?id=3630 两题非常类似,所以在这里一并做了. 1056题目大意: 如果一 ...
- SprimgMVC学习笔记(八)—— SpringMVC与前台json数据交互
一.两种交互形式 可以看出,前台传过来的方式有两种,一种是传json格式的数据过来,另一种就是在url的末尾传普通的key/value串过来,针对这两种方式,在Controller类中会有不同的解析, ...
- 09-排序3 Insertion or Heap Sort (25 分)
According to Wikipedia: Insertion sort iterates, consuming one input element each repetition, and gr ...
- 精简的网站reset和css通用样式库
一.CSS reset body{ line-height:1.4; color:#; font-family:arial; font-size: 12px; } input,textarea,sel ...
- Java String 字符串操作小结
// 转载加编辑 -- 21 Apr 2014 1. Java字符串中子串的查找 Java中字符串中子串的查找共有四种方法,如下: 1.int indexOf(String str) :返回第一次出现 ...
- day_08 文件操作
常用模式解释 open表示打开一个文件 f 变量, 操控XXX.txt文件的句柄 r:只读 w:只写 a:追加写入 b:byte,这种模式下,encoding不能用utf-8字符集 1. 文件的基本操 ...
- python 函数调用
##########定义函数######### 如果不主动调用函数,函数是不会执行的 def say_hello(): print 'hello1' print 'hello2' ...
- 使用Spring和JQuery实现视频文件的上传和播放
Spring MVC可以很方便用户进行WEB应用的开发,实现Model.View和Controller的分离,再结合Spring boot可以很方便.轻量级部署WEB应用,这里为大家介绍如何使用Spr ...
- 安装tomcat时遇到的问题
1.刚开始在eclipse配置的tomcat是免安装的,后来提示 所以后来配置了一个安装版的. 2.后来运行server发现报错:8080,8005,端口被占用,然后关闭xammp上的server,然 ...
- Selenium + Python操作IE 速度很慢的解决办法
IEDriverServer 64位换成32位 https://docs.seleniumhq.org/download/