有没有办法在循环中重用 Formatter 对象?
有没有办法在循环中重用格式化程序,或者我只是实例化并让垃圾收集器处理它? (这是一个Java问题)。请注意,如果我将实例化从循环中取出,则循环中先前迭代的格式化内容将被附加到。 Formatter.flush() 似乎只是刷新,正如它的名字一样,并没有提供允许重新使用干净的石板的好处。
例子:
for (...)
{
Formatter f = new Formatter();
f.format("%d %d\n", 1, 2);
myMethod(f.toString());
}
Is there a way to re-use a Formatter in a loop or do I simply instantiate and let the garbage collector deal with it? (This is a Java question). Note if I take instantiation out of the loop, the formatted content of previous iterations through the loop will get appended to. Formatter.flush() only seems to flush, true to its name and does not give the benefit of allowing a clean slate re-use.
Example:
for (...)
{
Formatter f = new Formatter();
f.format("%d %d\n", 1, 2);
myMethod(f.toString());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以这样使用它:
这将重用 Formatter 和 StringBuilder,这可能会或可能不会为您的用例带来性能提升。
You could use it like this:
This will reuse the Formatter and StringBuilder, which may or may not be a performance gain for your use case.
Formatter
的标准实现是“有状态的”,即使用它改变一些内部状态。这使得重用变得更加困难。您可以尝试以下几个选项:
如果这是您的代码,您可以添加一个
reset()
方法来清除内部状态。缺点:如果您忘记调用此方法,则会发生不好的事情。相反,如果更改内部状态,您可以在
format()
中返回格式化结果。由于您不再拥有内部状态,因此无需使用reset()
方法即可重用该对象,这使得使用起来更加安全但由于这是标准 API,因此您无法更改它。
只需在循环中创建新对象即可。在 Java 中创建对象非常便宜,并且忘记它们也不会花费任何费用。垃圾收集所花费的时间与活动对象的数量有关,而不是与代码产生的死亡对象的数量有关。基本上,GC 完全忽略任何不再与任何其他对象连接的对象。因此,即使您在循环中调用
new
十亿次,GC 也不会注意到。The standard implementation of
Formatter
is "stateful", that is using it changes some internal state. This makes it harder to reuse.There are several options which you can try:
If it was your code, you could add a
reset()
method to clear the internal state. Disadvantage: If you forget to call this method, bad things happen.Instead if changing the internal state, you could return the formatted result in
format()
. Since you don't have an internal state anymore, the object can be reused without areset()
method which makes it much more safe to useBut since that's a standard API, you can't change it.
Just create new objects in the loop. Creating objects in Java is pretty cheap and forgetting about them doesn't cost anything. The time spent in the garbage collection is relative to the number of living objects, not the amount of dead ones that your code produces. Basically, the GC is completely oblivious to any objects which are not connected to any other object anymore. So even if you call
new
a billion times in a loop, GC won't notice.只需实例化一个新的并让旧的被垃圾收集即可。
Just instantiate a new one and let the old one get garbage collected.