本文概述
- StringBuffer示例
- StringBuilder示例
- StringBuffer和StringBuilder的性能测试
下面列出了StringBuffer和StringBuilder之间的差异:
没有。 | StringBuffer | StringBuilder |
---|---|---|
1) | StringBuffer已同步, 即线程安全。这意味着两个线程不能同时调用StringBuffer的方法。 | StringBuilder是非同步的, 即不是线程安全的。这意味着两个线程可以同时调用StringBuilder的方法。 |
2) | StringBuffer的效率不如StringBuilder。 | StringBuilder比StringBuffer效率更高。 |
文章图片
StringBuffer示例
//Java Program to demonstrate the use of StringBuffer class.
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
hellojava
StringBuilder示例
//Java Program to demonstrate the use of StringBuilder class.
public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
}
}
hellojava
StringBuffer和StringBuilder的性能测试 让我们看一下检查StringBuffer和StringBuilder类性能的代码。
//Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.
public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0;
i<
10000;
i++){
sb.append("Tpoint");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0;
i<
10000;
i++){
sb2.append("Tpoint");
}
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");
}
}
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms
推荐阅读
- 如何创建不可变类()
- String和StringBuffer之间的区别
- Java可变参数(变量)
- Java静态导入
- Java的新功能介绍
- Java通用实例创建的类型推断
- try-with-resources语句
- ?算法题?面试题每日精进|蓝桥杯java怎么提交代码
- 蓝桥杯Python|蓝桥杯VIP题目免费提交,内含超详解,步步截图!!!