Search code examples
javafileoutputstream

Compare output stream performance


I have a serializable object and I want to write it down to file. Should I use ObjectOutputStream.writeObject() or convert it into a byte[] (using ObjectOutputStream) then use FileOutputStream.write()?

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))
objectOutputStream.writeObject(myObject);

or

ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out;
out = new ObjectOutputStream(byteOut);
out.writeObject(myObject);
new FileOutputStream(file).write(byteOut.toByteArray());

Solution

  • Buffering can improve performance by coalescing small writes into larger bulk writes. If you want to introduce buffering use a BufferedOutputStream, which does what you're doing with the byte array stream without changing downstream code.

    // Unbuffered
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
    
    // Buffered
    ObjectOutputStream outputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
    

    This way you can continue to use ObjectOutputStream without the rest of the code having to know whether the stream is buffered or unbuffered.

    As with any performance-related change, you should benchmark both approaches to see which performs better. Don't make changes like this without empirical testing. If you don't test, you're just guessing.