StringBuilder重用小技巧

作者在查看BigDecimal代码对字符串的处理时,发现其setLength()相关实现重用了StringBuilder,仅需重置count指针。同时通过Threadlocal与StringBuilder结合使用,提高了可用性,作者记录下这一有趣发现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天无意看到了 BigDecimal 代码里对字符串的处理,发现个有趣的事

 static class StringBuilderHelper {

        final StringBuilder sb;    // Placeholder for BigDecimal string
        final char[] cmpCharArray; // character array to place the intCompact

        StringBuilderHelper() {
            sb = new StringBuilder();
            // All non negative longs can be made to fit into 19 character array.
            cmpCharArray = new char[19];
        }

        // Accessors.
        //重用StringBuilder,通过重置stringBuilder 里边 count 指针来达到对象复用
        StringBuilder getStringBuilder() {
            sb.setLength(0);
            return sb;
        }
    ...
}

 setLength() 相关实现:

    public void setLength(int newLength) {
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        ensureCapacityInternal(newLength);

        if (count < newLength) {
            Arrays.fill(value, count, newLength, '\0');
        }

        count = newLength;
    }

这里实现了对StringBuilder的重用,只需要重置count指针。很nice的想法,记录下,同时通过Threadlocal+StringBuilder的使用,提高了可用性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值