2

I am reading XML files from a directory (containing thousands of files), processing the content and writing one output file for each input file. Is there a way of 're-pointing' an existing BufferedWriter instead of creating a new instance for each file?

...
    Scanner scanner;
    BufferedWriter writer;
    File outfile;
    for (File f: directory.ListFiles[]){
      scanner = new Scanner(f);
      outfile = ...;
      // processing input
      writer = new BufferedWriter(new FileWriter(new File(outfile)));
      // write the content
      writer.flush();
      writer.close();
    }

...

It seems a waste to have to create thousands of iterations of the Scanner and BufferedWriter.

casperOne
  • 73,706
  • 19
  • 184
  • 253
REardley
  • 21
  • 2
  • The JVM can detect if it can reuse the writer objects created... – dacwe Sep 02 '11 at 13:12
  • Object creation is very cheap, so there is no need to worry about creating the objects –  Sep 02 '11 at 13:55
  • `BufferedWriter` is an *extremely* lightweight class. Far more lightweight than the file that it wraps. – parsifal Sep 02 '11 at 13:59
  • A bigger problem is that you don't specify the encoding that you use to write the file. Do you know what your default encoding is? Can you guarantee that every consumer of your files will have the same encoding? If the answer to either of these questions "no," then you should use an `OutputStreamWriter` with an explicit encoding. – parsifal Sep 02 '11 at 14:00
  • @a_horse_with_no_name, I'm analyzing performance of my android application, and BufferedWriter allocation (or rather, the char[] allocation done in its constructor) is currently the biggest contributor to expensive GC_FOR_ALLOC passes, and very disruptive to my UI. The allocation is quite fast, but the impact on the system is heavy. – Chris Betti May 18 '15 at 19:12

1 Answers1

3

To me this would sound like a premature optimization. JVM is one of the smartest pieces of the software on the planet and can detect if your objects are short-lived. It can (and will) also perform a boatload of optimizations. Most likely any micro-optimizations you attempt to make will only result in poor performance.

Key to performance optimization is to measure, not to reason.

Lauri Piispanen
  • 2,067
  • 12
  • 20