Is there a way to reuse a Formatter object in a loop?

Is there a way to reuse Formatter in a loop or just instantiate and let the garbage collector handle it? (This is a Java question). Please note that if I take an instance from the loop, the formatted contents of the previous iterations through the loop will be added. Formatter.flush () only seems to be hidden, true to its name and does not allow to allow reuse of a blank slide.

Example:

for (...)
{
    Formatter f = new Formatter();
    f.format("%d %d\n", 1, 2);
    myMethod(f.toString());
}
+3
source share
4 answers

You can use it as follows:

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 result in the reuse of Formatter and StringBuilder, which may or may not be a performance gain for your use case.

+9

Formatter - "stateful", , - . .

, :

  • , reset(), . : , .

  • format(). , reset(),

API, .

. Java , . , , , , . , GC , - . new , GC .

+1

.

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

All Articles