java中用于处理字符串常用的有三个类:
java.lang.String
java.lang.StringBuffer
java.lang.StrungBuilder
三者共同之处:
都是final类,不允许被继承,主要是从性能和安全性上考虑的;防止其中的参数被参数修改影响到其他的应用。
StringBuffer是线程安全,可以不需要额外的同步用于多线程中;
StringBuilder是非线程安全,运行于多线程中就需要使用着单独同步处理,但是速度就比StringBuffer快多了;
StringBuffer与StringBuilder两者共同之处:
可以通过append、indert进行字符串的操作。
String实现了三个接口:Serializable
、Comparable<String>
、CarSequence
StringBuilder只实现了两个接口Serializable、CharSequence
,
相比之下String的实例可以通过compareTo方法进行比较,其他两个不可以。
这三个类之间的区别主要有两个方面,即运行速度和线程安全这两方面
- 首先说运行速度,或者说是执行速度,在这方面运行速度快慢为:StringBuilder > StringBuffer > String
- String最慢的原因:String为字符串常量,而StringBuilder和StringBuffer均为字符串变量,即String对象一旦创建之后该对象是不可更改的,但后两者的对象是变量,是可以更改的。
我们可以根据源码中的一段注释来理解:
* Strings are constant; their values cannot be changed after they
* are created. String buffers support mutable strings.
* Because String objects are immutable they can be shared.
翻译为:
字符串是常量;创建后,它们的值不能更改。字符串缓冲区支持可变字符串。 由于String对象是不可变的,因此可以共享它们。
看下面的代码能够很直观的看出执行速度差距:
long str1=System.nanoTime();
String str="hello";
str=str+"world";
System.out.println(str+"-------"+"str使用时间:"+(System.nanoTime()-str1)+"ns");
long str2=System.nanoTime();
StringBuffer stringBuffer=new StringBuffer().append("hello").append("world");
System.out.println(stringBuffer.toString()+"-------"+"stringBuffer使用时间:"+(System.nanoTime()-str2)+"ns");
long str3=System.nanoTime();
StringBuilder stringBuilder=new StringBuilder().append("hello").append("world");
System.out.println(stringBuilder.toString()+"-------"+"stringBuilder使用时间:"+(System.nanoTime()-str3)+"ns");
结果:
helloworld——-str使用时间:125600ns
helloworld——-stringBuffer使用时间:95000ns
helloworld——-stringBuilder使用时间:8300ns
总结一下
String:适用于少量的字符串操作的情况
StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况
StringBuffer: 适用多线程下在字符缓冲区进行大量操作的情况
版权声明:本文为ly2708169628原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。