2

I wrote java a program to write millions of char(s) to a file, as following:

PrintWriter text_writer = new PrintWriter("SearchString.txt");
Random r = new Random();
for (int i = 0; i < NumChars; i++) {                
    text_writer.print(alphabet.charAt(r.nextInt(N));
}

I knew, I was doing a bad programming and I was not considering any performance degradation. The program was also running fast enough, i.e., was completing the loop of 10 million in about a minute or so.

A colleague, not working in Java, commented that my code was okay, because, it actually is not performing 10 million IOs. It most probably is being handled by an intermediate buffer automatically and optimally.

I have googled but could not see any such thing.

My question is:

Is that true? if yes, then, how is it handled?

So, should I consider this practise fine?

I am not asking about how to make it optimal. There is plenty of material on that.

tod
  • 1,539
  • 4
  • 17
  • 43
  • Please include where you define and instantiate the text_writer. PS: Don't use underscores in variable names in Java, use textWriter, or better still, name your variables after their usage rather than type. If you name by type, you'll be tempted to reuse objects, which is a "code smell" – Jeff Watkins May 25 '16 at 13:48

1 Answers1

4

This highly depends on how the PrintWriter is instantiated and the JRE. In your example when using the PrintWriter(String) constructor, we can see in the JDK sources that it internally does:

new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
             false

So it will be buffered. At least in my version of Oracle's JRE, but this is entirely an implementation detail and may vary across JRE vendors and even versions of the same vendor. So my recommendation is to instantiate the PrintWriter using the PrintWriter(Writer) constructor and pass a buffered writer as a parameter. In that way you can be sure that it will always be buffered.


So, should I consider this practise fine?

No. If you take a look at the implementation of the write(char) method, you'll see that it does a null check + synchronization. The write(char[]) method actually does the same, but once for the whole array, so using the bulk methods will save you thousand of needless method calls, checks and synchronisations along the way.

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82