简体   繁体   English

设置StringBuilder对象的最佳方法是什么?

[英]What's the best way to set a StringBuilder object?

I created a StringBuilder object without any value and appended some values afterwards. 我创建了一个没有任何值的StringBuilder对象,然后追加了一些值。 I later wanted to replace the object with an entirely different string. 后来我想用一个完全不同的字符串替换该对象。

Here's the code: 这是代码:

StringBuilder finalVersion = new StringBuilder();
finalVersion.append("6.0")
for (int i = 0; i < list.length(); i++) {
    if(/*...*/){
       finalVersion.append(".2");
    } else {
       finalVersion.append(".1");
    }
    if (/*...*/) {
        if (/*...*/) {
            finalVersion = new StringBuilder("Invalid parameter"));
         }
    }
}

What I've done is I created a new object to change the value, but perhaps there is a better approach without using stringBuilder.setLength(0); 我所做的是创建了一个新对象来更改值,但是也许有更好的方法而不使用stringBuilder.setLength(0); .

Could someone help? 有人可以帮忙吗?

To solve it I created a new object to change the value but I guess there is a better approach without use sb.setLength(0) 为了解决这个问题,我创建了一个新对象来更改值,但是我猜想有一个更好的方法而不使用sb.setLength(0)

Both of those are good approaches. 两者都是好的方法。 Another is sb.delete(0, sb.length()) . 另一个是sb.delete(0, sb.length())

And when you want to replace the existing string content, sb.replace(0, sb.length(), "new content") is another option. 当您要替换现有的字符串内容时, sb.replace(0, sb.length(), "new content")是另一种选择。

It really depends what your goal is: 这实际上取决于您的目标是:

  • Calling new StringBuffer(...) will give you a freshly allocated object with either the default capacity or a capacity that you specify. 调用new StringBuffer(...)将为您提供一个具有默认容量或您指定容量的新分配对象。

  • The setLength , delete and replace approaches will recycle the existing object. setLengthdeletereplace方法将回收现有对象。 This has advantages and disadvantages. 这具有优点和缺点。

    • On the plus side, you don't allocate a new object 1 ... so less garbage. 从好的方面来说,您不必分配新对象1 ...这样可以减少垃圾。

    • On the minus side, the string buffer uses the same amount of space as before, whether or not it needs to. 在不利的一面,无论是否需要 ,字符串缓冲区都使用与以前相同的空间量。 Also, if you do this repeatedly, the chances are that the buffer and its backing array will be tenured by the GC, adding to the long-term memory load. 另外,如果您重复执行此操作,则GC可能会占用缓冲区及其后备阵列,这会增加长期的内存负载。 You can free the unused capacity by calling sb.trimToSize() , but that is liable to cause a reallocation; 您可以通过调用sb.trimToSize()释放未使用的容量,但这会导致重新分配; ie what you were trying to avoid by not using new . 即您试图通过不使用new来避免的情况。

My advice would be to use new unless either the context means that you can't, or your profiling tells you that new is generating too much garbage. 我的建议是使用new 除非上下文意味着您不能这样做,或者您的剖析告诉您new产生了太多的垃圾。

Looking at the code 2 , I think that setLength should be marginally faster than delete for emptying a StringBuffer . 看代码2 ,我认为setLength应该比delete快一些,以清空StringBuffer It gets more complicated when you are replacing the contents with new contents. 用新内容替换内容时,它会变得更加复杂。 Now you are comparing 现在您正在比较

   sb.setLength(); sb.append("new content");

versus

   sb.replace(0, sb.length(), "new content");

It needs to be measured ... if you care enough 3 about performance to be comparing the cases. 它需要进行测量...如果您足够在意性能3以进行比较。


1 - Unless the replacement string is large enough that the buffer needs to grow to hold it. 1-除非替换字符串足够大,否则缓冲区需要增长以容纳它。

2 - By my reading of various versions of the StringBuilder and AbstractStringBuilder code, the delete method will always call System.arraycopy . 2-通过阅读StringBuilderAbstractStringBuilder代码的各种版本, delete方法将始终调用System.arraycopy However, to understand the performance impact, one would need to benchmark this carefully for different sizes of StringBuilder and across different Java versions. 但是,要了解性能影响,就需要针对不同大小的StringBuilder和跨不同Java版本对此进行仔细的基准测试。

3 - Actually, if you need to care. 3-实际上,如果您需要护理。 Beware the evils of premature optimization. 提防过早优化的弊端。

You can use replace . 您可以使用replace This method doesn't create a new StringBuilder object. 此方法不会创建新的StringBuilder对象。

builder.replace(0, b.length(), "Invalid parameter");

Or, if doing it in two statements is fine with you, you can setLength(0) , then append . 或者,如果您可以用两个语句来完成此操作,则可以setLength(0) ,然后append

But really, you shouldn't worry about creating a new StringBuilder unless you actually encounter performance problems. 但实际上,除非您确实遇到性能问题,否则您不必担心创建新的StringBuilder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将结果集映射到对象的最佳方法是什么 - What's the best way to map the resultset to object 填充列表的最佳方法是什么 <Object> ? - What's the best way to populate List<Object>? 检查对象属性是否为空的最佳方法是什么? - what's the best way to check if an object's attribute is empty? 在hadoop中进行集合成员资格测试的最佳方法是什么? - What's the best way to do set-membership tests in hadoop? 在HBase中存储和更新Set的最佳方法是什么? - What's the best way to store and update a Set in HBase? 在单元测试中验证 Set 值的最佳方法是什么? - What's the best way to validate the values of a Set in a unit test? (de)将Java对象序列化为文件的最佳方法是什么 - What's the best way to (de)serialize a Java object to file 在 Java 中检查对象及其成员为空的最佳方法是什么 - What is the best way to check object and it's members are null in Java 获取数组类型的Class对象的最佳方法是什么? - What's the best way to get a Class object for an array type? 将颜色 object“四舍五入”到最接近的颜色常数的最佳方法是什么? - What's the best way to “round” a Color object to the nearest Color Constant?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM