如何清除或清空StringBuilder? [重复]

本文讨论了在Java中清空StringBuilder的几种方法,包括使用`StringBuilder.delete(0, length)`、直接赋值为new StringBuilder()等。不同方法在性能和适用场景上有所区别,例如频繁操作时避免滥用GC。" 121608130,10714478,Oracle存储过程的创建、调用与删除详解,"['数据库', 'SQL', 'Oracle']
摘要由CSDN通过智能技术生成

本文翻译自:How can I clear or empty a StringBuilder? [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

I'm using a StringBuilder in a loop and every x iterations I want to empty it and start with an empty StringBuilder , but I can't see any method similar to the .NET StringBuilder.Clear in the documentation, just the delete method which seems overly complicated. 我在循环中使用StringBuilder ,每隔x次迭代,我想将其清空并从一个空的StringBuilder开始,但是在文档中看不到任何类似于.NET StringBuilder.Clear的方法,只是删除方法似乎过于复杂。

So what is the best way to clean out a StringBuilder in Java? 那么用Java清理StringBuilder的最佳方法是什么?


#1楼

参考:https://stackoom.com/question/LmoC/如何清除或清空StringBuilder-重复


#2楼

If performance is the main concern then the irony, in my opinion, is the Java constructs to format the text that goes into the buffer, will be far more time consuming on the CPU than the allocation/reallocation/garbage collection ... well, possibly not the GC (garbage collection) depending on how many builders you create and discard. 如果主要考虑性能,那么我认为具有讽刺意味的是,用于格式化进入缓冲区的文本的Java构造将比分配/重新分配/垃圾回收在CPU上花费更多的时间……嗯,可能不是GC(垃圾收集),具体取决于您创建和丢弃的构建器数量。

But simply appending a compound string ( "Hello World of " + 6E9 + " earthlings." ) to the buffer is likely to make the whole matter inconsequential. 但是,仅将复合字符串( "Hello World of " + 6E9 + " earthlings." )添加到缓冲区很可能会使整个问题变得无关紧要。

And, really, if an instance of StringBuilder is involved, then the content is complex and/or longer than a simple String str = "Hi"; 而且,实际上,如果涉及到StringBuilder的实例,则内容比简单的String str = "Hi";复杂和/或更长String str = "Hi"; (never mind that Java probably uses a builder in the background anyway). (没关系,Java可能仍会在后台使用构建器)。

Personally, I try not to abuse the GC. 我个人不尝试滥用GC。 So if it's something that's going to be used a lot in a rapid fire scenario - like, say, writing debug output messages - I just assume declare it elsewhere and zero it out for reuse. 因此,如果在快速启动的场景中将大量使用它(例如,编写调试输出消息),我只是假设在其他地方声明它并将其归零以供重用。

class MyLogger {
    StringBuilder strBldr = new StringBuilder(256);

    public void logMsg( String stuff, SomeLogWriterClass log ) {

        // zero out strBldr's internal index count, not every
        // index in strBldr's internal buffer
        strBldr.setLength(0);

        // ... append status level
        strBldr.append("Info");

        // ... append ' ' followed by timestamp
        // assuming getTimestamp() returns a String
        strBldr.append(' ').append(getTimestamp());

        // ... append ':' followed by user message
        strBldr.append(':').append(msg);

        log.write(strBldr.toString());
    }
}

#3楼

You should use sb.delete(0, sb.length()) or sb.setLength(0) and NOT create a new StringBuilder(). 您应该使用sb.delete(0, sb.length())sb.setLength(0)而不要创建新的StringBuilder()。

See this related post for performance: Is it better to reuse a StringBuilder in a loop? 有关性能,请参见此相关文章: 在循环中重用StringBuilder更好吗?


#4楼

StringBuilder s = new StringBuilder();
s.append("a");
s.append("a");
// System.out.print(s); is return "aa"
s.delete(0, s.length());
System.out.print(s.length()); // is return 0

is the easy way. 是简单的方法。


#5楼

I think many of the answers here may be missing a quality method included in StringBuilder : .delete(int start, [int] end) . 我认为这里的许多答案可能缺少StringBuilder包含的质量方法: .delete(int start, [int] end) I know this is a late reply; 我知道这是一个迟来的答复; however, this should be made known (and explained a bit more thoroughly). 但是,应该知道这一点(并进行更彻底的解释)。

Let's say you have a StringBuilder table - which you wish to modify, dynamically, throughout your program (one I am working on right now does this), eg 假设您有一个StringBuilder表-您希望在整个程序中动态修改它(我现在正在处理的一个表),例如

StringBuilder table = new StringBuilder();

If you are looping through the method and alter the content, use the content, then wish to discard the content to "clean up" the StringBuilder for the next iteration, you can delete it's contents, eg 如果要遍历该方法并更改内容,请使用该内容,然后希望丢弃该内容以“清理” StringBuilder进行下一次迭代,则可以删除其内容,例如

table.delete(int start, int end). 

start and end being the indices of the chars you wish to remove. 开始和结束是您要删除的字符的索引。 Don't know the length in chars and want to delete the whole thing? 不知道字符长度,想删除整个内容吗?

table.delete(0, table.length());

NOW, for the kicker. 现在,为踢球者。 StringBuilders , as mentioned previously, take a lot of overhead when altered frequently (and can cause safety issues with regard to threading); 如前所述, StringBuilders在频繁更改时会占用大量开销(并且可能导致线程安全问题); therefore, use StringBuffer - same as StringBuilder (with a few exceptions) - if your StringBuilder is used for the purpose of interfacing with the user. 因此,使用StringBuffer -一样StringBuilder (只有少数例外) -如果您StringBuilder用于与用户交互的目的。


#6楼

I'll vote for sb.setLength(0); 我将投票给sb.setLength(0); not only because it's one function call, but because it doesn't actually copy the array into another array like sb.delete(0, builder.length()); 不仅因为它是一个函数调用,而且因为它实际上没有将数组复制到另一个数组中,例如sb.delete(0, builder.length()); . It just fill the remaining characters to be 0 and set the length variable to the new length. 它只是将其余字符填充为0,并将length变量设置为新的长度。

You can take a look into their implementation to validate my point from here at setLength function and delete0 function. 您可以在此处通过setLength函数和delete0函数了解它们的实现,以验证我的观点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值