zoukankan      html  css  js  c++  java
  • StringBuilder底层代码研究

    之前看几个微博大V讨论String拼接效率问题。今天好不容易闲下来就看了看StringBuilder的底层拼接到底怎么回事。

    java 版本是1.6版

    通过StringBuilder追踪到上层抽象类:AbstractStringBuilder,

    String保存在AbstractStringBuilder中是一个名为【value】的char类型数组

    然后查看了抽象类的append方法

    public AbstractStringBuilder append(String str) {
        //校验
        if (str == null) 
            str = "null";
        int len = str.length();
        if (len == 0)
            return this;
        
        //新长度
        int newCount = count + len;
        
        //确定是否需要给当前的value扩容
        if (newCount > value.length)
            expandCapacity(newCount);
        
        //把字符串转化为char[]。然后增加到value后方
        str.getChars(0, len, value, count);
        count = newCount;
        return this;
        }
        
        
    void expandCapacity(int minimumCapacity) {
            //自动构造长度为两倍当前长度
            int newCapacity = (value.length + 1) * 2;
            //如果自动构造长度超长则只能取最大Integer长度
            if (newCapacity < 0) {
                newCapacity = Integer.MAX_VALUE;
            //如果新长度大于自动构造长度那么构造长度为新长度
            } else if (minimumCapacity > newCapacity) {
            newCapacity = minimumCapacity;
            }
            //字符串相关数组扩容
            value = Arrays.copyOf(value, newCapacity);
        }

    这里可以看出拼接字符串实际上是字符数组的扩容与拷贝。

    而且每次调用一次字符容量最起码就会在当前基础上翻倍。

    即:n*2的次方。直到长度达到2147483647

    所以如何合理拼接字符串呢?

  • 相关阅读:
    函数式宏定义与普通函数
    linux之sort用法
    HDU 4390 Number Sequence 容斥原理
    HDU 4407 Sum 容斥原理
    HDU 4059 The Boss on Mars 容斥原理
    UVA12653 Buses
    UVA 12651 Triangles
    UVA 10892
    HDU 4292 Food
    HDU 4288 Coder
  • 原文地址:https://www.cnblogs.com/blackdeng/p/7799593.html
Copyright © 2011-2022 走看看