简体   繁体   中英

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

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());
}

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM