StringBuilder - 重置或创建新的 [英] StringBuilder - Reset or create a new
问题描述
我有一个条件,StringBuilder保持存储与大平面文件(100的MB)中的模式匹配的行。但是在达到条件后,我将StringBuilder varialble的内容写入文本文件。
I have a condition that a StringBuilder keeps storing lines matching a pattern from a large flat file (100's of MB). However after reaching a condition I write the content of the StringBuilder varialble to a textfile.
现在我想知道是否应该通过重置对象来使用相同的变量 - >
Now I wonder if I should use the same variable by resetting the object ->
stringBuilder.delete(0,stringBuilder.length())
OR
stringBuilder=new StringBuilder();
请注意,就性能和OOM问题而言,您认为哪种方式更好。
Please suggest which would do you think is better as far as both performance and OOM issues are concerned.
推荐答案
我认为 StringBuilder #delete(start,end)
仍然很贵请致电:
I think StringBuilder#delete(start, end)
is still expensive call, you should do:
stringBuilder.setLength(0);
重置它。
更新:查看 源代码 StringBuilder
似乎 setLength(int)
保留旧缓冲区,最好调用: StringBuilder#trimToSize()
在上述通话后 尝试减少用于字符序列的存储空间
。
UPDATE: After looking at source code of StringBuilder
It seems setLength(int)
leaves old buffer intact and it is better to call: StringBuilder#trimToSize()
after above call which attempts to reduce storage used for the character sequence
.
所以这样的事情会更有效率:
So something like this would be more efficient:
stringBuilder.setLength(0); // set length of buffer to 0
stringBuilder.trimToSize(); // trim the underlying buffer
这篇关于StringBuilder - 重置或创建新的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!