Sean Sean - 1 year ago 126
Java Question

Java - DataOutputStream writeLong\Byte\Double\Int Speed

I implemented a way to write primitive Java types to a binary output file using

's writeX methods, but I'm observing 60-fold slower performance relative to a previous implementation that writes to a text file via a

I create my output stream like so:

DataOutputStream outFile = new DataOutputStream(new FileOutputStream("fileLoc"));

I use this method to write to such streams:

public static void writeFunctionPoint (DataOutputStream outFile, FunctFileSortCriterion functPt) throws IOException
outFile.writeLong (functPt.time);
outFile.writeBytes (functPt.dfid);
outFile.writeDouble (functPt.value);
outFile.writeInt (functPt.qualifier);

} // end method writeFunctionPoint

Why is my new approach so much slower than my old one?

Answer Source

You started out using a BufferedWriter and switched to an unbuffered OutputStream. I/O buffering can have a tremendous impact on performance, especially if you're writing a large number of small pieces. Insert a BufferedOutputStream:

DataOutputStream outFile = new DataOutputStream(
        new BufferedOutputStream(
        new FileOutputStream("fileLoc")));

That ought to get you a substantial speedup vs. where you are now. You can also try tweaking the buffer size to tune the performance a bit. I can't say how that will compare to your original BufferedWriter-based implementation, however; I'd guess it will be at least comparable, but performance is very hard to predict in general. It is essential to test.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download