is there a way to re-use a Formatter object within a loop?

落爺英雄遲暮 提交于 2019-12-05 20:12:43

You could use it like this:

StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);

for (...)
{
    f.format("%d %d\n", 1, 2);
    myMethod(sb.toString());
    sb.setLength(0);
}

This will reuse the Formatter and StringBuilder, which may or may not be a performance gain for your use case.

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:

  1. 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.

  2. 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 a reset() method which makes it much more safe to use

But 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.

for (...) {
    myMethod(String.format("%d %d\n", 1, 2));
}
jcomeau_ictx

Just instantiate a new one and let the old one get garbage collected.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!