String,StringBuffer和StringBuilder 的区别

String,StringBuffer和StringBuilder 的区别

1、String 中使用 final 关键字字符数组保存字符串,对象是不可变的,也就可以理解为常量,线程安全

2、StringBuilder 与 StringBuffer 都继承自 AbstractStringBuilder 类,在 AbstractStringBuilder 中也是使用字符数组保存字符串 char[]value 但是没有用 final 关键字修饰,所以这两种对象都是可变的

3、StringBuffer 对方法加了同步锁或者对调用的方法加了同步锁,所以是线程安全的。StringBuilder 并没有对方法进行加同步锁,所以是非线程安全的。

使用String操作对象计算耗时:12ms

public class App {

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        String str = "";
        for(int i = 0; i < 1000; i++) {
            str += (i+"#");
        }
        long t2 = System.currentTimeMillis();
        System.out.println(str);
        System.out.println("耗时:"+(t2-t1)+" ms");
    }

}

在这里插入图片描述
使用StringBuffer操作对象计算耗时:3ms

public class App {

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        StringBuffer str = new StringBuffer();
        for(int i = 0; i < 1000; i++) {
            str.append(i+"#");
        }
        long t2 = System.currentTimeMillis();
        System.out.println(str);
        System.out.println("耗时:"+(t2-t1)+" ms");
    }

}

在这里插入图片描述
使用StringBuilder操作对象计算耗时:2ms

public class App {

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        StringBuilder str = new StringBuilder();
        for(int i = 0; i < 1000; i++) {
            str.append(i+"#");
        }
        long t2 = System.currentTimeMillis();
        System.out.println(str);
        System.out.println("耗时:"+(t2-t1)+" ms");
    }

}

在这里插入图片描述

对于三者使用的总结

  1. 操作少量的数据 = String
  2. 单线程操作字符串缓冲区下操作大量数据 = StringBuilder
  3. 多线程操作字符串缓冲区下操作大量数据 = StringBuffer
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值