本文翻译自:How can I clear or empty a StringBuilder? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
- Clearing a string buffer/builder after loop 8 answers 循环 8回答 后清除字符串缓冲区/生成器
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
函数了解它们的实现,以验证我的观点。