Java数据类型—StringBuilder与StringBuffer「建议收藏」

Java数据类型—StringBuilder与StringBuffer「建议收藏」StringBuilder与StringBuffer作用就是用来处理字符串,但String类本身也具备很多方法可以用来处理字符串,那么为什么还要引入这两个类呢?前面我们讲解到String对象的不可变性,以及它的不足那就是创建新的对象,因为它是不可变的,所以你对它的操作逻辑就体现在另外一个对象里,那就是你的操作新创建的对象。…

大家好,又见面了,我是你们的朋友全栈君。

StringBuilder与StringBuffer

StringBuilder与StringBuffer作用就是用来处理字符串,但String类本身也具备很多方法可以用来处理字符串,那么为什么还要引入这两个类呢?前面我们讲解到String 对象的不可变性,以及它的不足那就是创建新的对象,具体你可以查看文章String进阶之不可变性,因为它是不可变的,所以你对它的操作逻辑就体现在另外一个对象里,那就是你的操作新创建的对象。

这种操作最常见的就是字符串的拼接,所以我们几天学习的这两个类都是为了解决这个问题的,那既然都是为了解决这个问题的,为什么会有两个类的,我们后面慢慢分析

初识

首先看下面的例子

    @Test
    public void testPerformance(){ 
   
        String str0 = "hello,world";

        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) { 
   
            str0 += i;
        }
        System.out.println(System.currentTimeMillis() - start);

        StringBuilder sb = new StringBuilder("hello,world");
        long start1 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) { 
   
            sb.append(i);
        }
        System.out.println(System.currentTimeMillis() - start1);

        StringBuffer sbf = new StringBuffer("hello,world");
        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) { 
   
            sbf.append(i);
        }
        System.out.println(System.currentTimeMillis() - start2);
    }

上述代码中3处循环完成了同样的功能,字符串拼接,执行的结果如下:

38833
4
4

可以看出执行时间差别很大,为了解决String不擅长的大量字符串拼接这种业务场景,所以我们引入了StringBuffer和StringBuilder.

首先我们分析一下为什么String在大量字符串拼接这种场景下这么慢?其实前面我们已经说到了,这我我们再解释一下

因为String本身不可变,我们对String的任何操作都会返回一个新的对象,然后当前String变量指向新的对象,而原来的String对象就会被GC回收,那么在循环中就会大量快速的创建新的对象,大量原来的对象会不断的被GC回收,消耗的时间是非常恐怖的,而且内存占用非常大。

但是我们从输出结果看到另外一个问题,那就是StringBuffer与StringBuilder的允许时间基本一致,那为什么需要定义两个功能相似的类呢?

接下来我们再看一段代码

    @Test
    public void testSafe() throws InterruptedException { 
   
        String str0 = "hello,world";

        StringBuilder sb = new StringBuilder(str0);
        for (int i = 0; i < 100; i++) { 
   
            new Thread(() -> { 
   
                try { 
   
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) { 
   
                    e.printStackTrace();
                }
                sb.append("a");
            }).start();
        }


        StringBuffer sbf = new StringBuffer(str0);
        for (int i = 0; i < 100; i++) { 
   
            new Thread(() -> { 
   
                try { 
   
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) { 
   
                    e.printStackTrace();
                }
                sbf.append("a");
            }).start();
        }
        // 等待工作线程运行结束
        while (Thread.activeCount()>2){ 
   

        }
        System.out.println("StringBuilder:"+sb.toString().length());
        System.out.println("StringBuffer:"+sbf.toString().length());
    }

输出结果

StringBuilder:109
StringBuffer:111

看出什么了吗,本来拼接完程度应该是111的,但是现在呢,StringBuilder是109,说明了StringBuilder不是安全的,也就是说再多线程的环境下,我们应该使用StringBuffer

下面我们对比了String、StringBuffer与StringBuilder的区别

String StringBuffer StringBuilder
final修饰,不可继承 final修饰,不可继承 final修饰,不可继承
字符串常量,创建后不可变 字符串变量,可动态修改 字符串变量,可动态修改
不存在线程安全问题 线程安全,所有public方法由synchronized修改 线程不安全
大量字符串拼接效率最低 大量字符串拼接效率非常高 大量字符串拼接效率最高

StringBuffer与StringBuilder实现非常类似,下面以StringBuilder简单说明一下append()方法基本原理

源码剖析

这里我们以StringBuilder为例,

1. StringBuilder的构造方法

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(100);

StringBuilder对字符串的操作是通过char[]来实现的,通过默认构造器创建的StringBuilder,其内部创建的char[]的默认长度为16,当然可以调用重载的构造器传递初始长度(推荐这样,因为这样可以减少数组扩容次数,提高效率)。

     */
    public StringBuilder() { 
   
        super(16);
    }

    /** * Constructs a string builder with no characters in it and an * initial capacity specified by the {@code capacity} argument. * * @param capacity the initial capacity. * @throws NegativeArraySizeException if the {@code capacity} * argument is less than {@code 0}. */
    public StringBuilder(int capacity) { 
   
        super(capacity);
    }

    /** * Constructs a string builder initialized to the contents of the * specified string. The initial capacity of the string builder is * {@code 16} plus the length of the string argument. * * @param str the initial contents of the buffer. */
    public StringBuilder(String str) { 
   
        super(str.length() + 16);
        append(str);
    }

    /** * Constructs a string builder that contains the same characters * as the specified {@code CharSequence}. The initial capacity of * the string builder is {@code 16} plus the length of the * {@code CharSequence} argument. * * @param seq the sequence to copy. */
    public StringBuilder(CharSequence seq) { 
   
        this(seq.length() + 16);
        append(seq);
    }

2. StringBuilder的append()方法

每次调用append(str)方法时,会首先判断数组长度是否足以添加传递来的字符串

/** * Appends the specified string to this character sequence. * <p> * The characters of the {@code String} argument are appended, in * order, increasing the length of this sequence by the length of the * argument. If {@code str} is {@code null}, then the four * characters {@code "null"} are appended. * * @param str a string. * @return a reference to this object. */
public AbstractStringBuilder append(String str) { 
   
    if (str == null)
        return appendNull();
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}
/** * For positive values of {@code minimumCapacity}, this method * behaves like {@code ensureCapacity}, however it is never * synchronized. * If {@code minimumCapacity} is non positive due to numeric * overflow, this method throws {@code OutOfMemoryError}. */
private void ensureCapacityInternal(int minimumCapacity) { 
   
    // overflow-conscious code
    if (minimumCapacity - value.length > 0) { 
   
        value = Arrays.copyOf(value,
                newCapacity(minimumCapacity));
    }
}

如果传递的字符串长度 + 数组已存放的字符的长度 > 数组的长度,这时就需要进行数据扩容了

/** * Returns a capacity at least as large as the given minimum capacity. * Returns the current capacity increased by the same amount + 2 if * that suffices. * Will not return a capacity greater than {@code MAX_ARRAY_SIZE} * unless the given minimum capacity is greater than that. * * @param minCapacity the desired minimum capacity * @throws OutOfMemoryError if minCapacity is less than zero or * greater than Integer.MAX_VALUE */
private int newCapacity(int minCapacity) { 
   
    // overflow-conscious code
    int newCapacity = (value.length << 1) + 2;
    if (newCapacity - minCapacity < 0) { 
   
        newCapacity = minCapacity;
    }
    return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
        ? hugeCapacity(minCapacity)
        : newCapacity;
}

扩容规则如下:默认将数组长度设置为“ (当前数组长度 * 2) + 2”,但如果按此规则扩容后的数组也不足以添加新的字符串,就需要将数组长度设置为“数组内字符长度 + 传递的字符串长度”。

因此假如我们知道拼接的字符串大概长度有100多字符,我们就可以设置初始长度150或200,这样就可以避免或减少数组扩容的次数,从而提高效率。

总结

  1. StringBuilder与StringBuffer 都是为了解决大量字符串拼接时的性能问题,其实就是为了解决String类在拼接过程中产生的大量对象的问题,因为这会导致大量内内存分配和GC 问题
  2. StringBuilder与StringBuffer 二者之间的主要区别是线程是否安全,StringBuffer 通过对方法添加synchronized关键字保证了线程安全。
  3. StringBuilder与StringBuffer底层都是依赖字符数组实现的,不同于String 的是String 底层的字符数组是不可变的,也就是final 修饰的,其实这就是StringBuilder与StringBuffer可变的原因,动态扩展字符数组来实现的。
  4. 为了提高StringBuilder与StringBuffer的性能我们可以通过设置合适的容量来避免数组库容。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/153409.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Z平台-开源免费的JAVA快速开发平台

    Z平台-开源免费的JAVA快速开发平台Z平台是开源免费的JavaWeb快速开发平台。通过Z平台集成开发环境,以零编码、动态配置的方式能够快速开发出各类Web管理系统。Z平台框架组成所用到的各种功能组件与框架,都是开源免费的,不涉及到版权问题,商业与非商业项目都可以使用。

    2022年5月14日
    50
  • 怎么用python打开csv文件_使用Python从CSV文件读取数据

    怎么用python打开csv文件_使用Python从CSV文件读取数据CSV文件,也就是Comma-separatedValue文件,用sublime打开是这样(数据下载见文末):如果用excel打开是这样(千万别点保存,保存就有问题):来看看怎么打开,如果安装了anaconda,我们先打开JupyterNotebook,新建一个ipynb文件:我们看完数据了,应该从哪里开始?当然是从python官方文档开始!先搜下csv,找到不少结果,csv是python…

    2022年7月20日
    21
  • java web 前端开发框架和流程「建议收藏」

    java web 前端开发框架和流程「建议收藏」1 通常JavaWeb开发框架举个例子,对于广告系统的来说,我们先不管一些job,byOminentShopperHelper”style=”color:rgb(59,115,175);border:none!important;display:inline-block!important;float:none!important;font-weight

    2022年7月9日
    23
  • PAT准备之2018.7.24

    昨天被我划水滑过去了,今天终于完成了救赎,基本没有划水,一直在认真的学习,今天也做了不少题,发现自己还是有很多知识点薄弱的地方,还是基础不太好吧,以前总觉得自己这些东西都会,结果发现真到自己用的时候,真的是不会。。。唉!这个暑假再把基础知识补一补吧。今天也是做了三道题。如下1007MaximumSubsequenceSum(25)(25分)Givenasequenceo…

    2022年4月9日
    49
  • 以树状结构输出计算机某个指定文件夹下的所有的文件和子文件夹名称

    以树状结构输出计算机某个指定文件夹下的所有的文件和子文件夹名称

    2021年7月17日
    66
  • Ubuntu 搭建opengrok 流程

    Ubuntu 搭建opengrok 流程opengrok平台搭建流程软件下载链接:https://pan.baidu.com/s/1kCeXNlj2l3FujyMza3rM0w提取码:iniy搭建前的准备电脑系统电脑系统推荐使用ubuntu16,这版系统较为稳定。细节未更新python环境推荐使用python2.7及以上版本,这一版本相对稳定,python安装细节未更新java环境推荐使用JDK1.8及以上版本,具体安装细节未更新通过java-version和javac-version可以查看版本。Ope

    2022年5月27日
    75

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号