[英]Java Char Buffer that automatically grows and can be re-used
Hello Java Developers: 您好Java开发人员:
I'm looking for a built in class to store a sequence of characters. 我正在寻找一个内置的类来存储字符序列。 It needs to meet the following criteria: 它需要满足以下条件:
I've found several options that meet some of these requirements but not all of them. 我找到了一些满足其中一些要求的选项,但并非全部。 For instance: 例如:
Am I misinterpreting the documentation for one of these classes, or does someone out there know of a data structure that meets all 4 criteria? 我是否误解了其中一个类的文档,还是那里的某个人知道满足所有这四个条件的数据结构?
Edit: By criteria 3, I don't mean free memory to GC. 编辑:按条件3,我并不是说要释放GC的内存。
I'm in the situation where I need to repeatedly allocate and de-allocate several of these buffers. 我处于需要重复分配和取消分配其中一些缓冲区的情况。 In my use case, these buffers end up being fairly large (~ 100 KB) and I would have several threads using such buffers. 在我的用例中,这些缓冲区最终会变得很大(〜100 KB),我将有多个线程使用此类缓冲区。
I'm aware that I could just create a buffer, use it and then have it GC-ed when I'm done. 我知道我可以创建一个缓冲区,使用它,然后在完成后进行GC处理。 However, I've found that the JVM garbage collector runs quite slowly when you are constantly allocating and de-allocating a large percent of the JVM (and physical machine's) memory. 但是,我发现当您不断分配和取消分配大部分JVM(和物理机)内存时,JVM垃圾收集器的运行速度非常慢。 I've found speed improvements when I start micromanaging the memory (like one can do in C++) by allocating a buffer once and then re-using it (thus triggering garbage collection less frequently). 当我开始微管理内存(就像在C ++中可以做到的那样)时,我发现速度得到了提高,方法是分配一次缓冲区,然后重新使用它(因此触发垃圾回收的频率降低)。
StringBuilder/StringBuffer should satisfy 3 fine since delete(...)
should do what you need. StringBuilder / StringBuffer应该满足3的要求,因为delete(...)
应该可以满足您的要求。 Or why not simply create a new instance and let the old one be GC'd? 还是为什么不简单地创建一个新实例并让旧实例成为GC?
StringBuffer可以删除其内容
buffer.delete(0, buffer.length());
Solution that I've found: StringBuilder has .setLength(0) which I can use to get the buffer to start re-writing contents. 我发现的解决方案:StringBuilder具有.setLength(0),可用来获取缓冲区以开始重写内容。
(A dedicated .reset() method would have been nice.) (专用的.reset()方法会很好。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.