javaperformanceexcelapache-poi

java: ByteArrayOutputStream.toByteArray() performance


I am writing out a poi workbook to a ByteArrayOutputStream in order to get the bytes and send them over in a soap message.

Getting the ByteArrayOutputStream is fine, but calling .toByteArray() is very slow and uses up a lot of cpu.
The workbook i am trying to convert is very large.

Does anybody have any suggestions on how I could speed this up?

Thank you, Jason


Solution

  • Are you declaring a buffer size when creating the ByteArrayOutputStream object? If not, you're spending the time to expand the buffer and copy over the bytes each time it expands. Set the final size needed in the constructor and you should see some speed improvement for a large file.

    From Oracle Documentation: Constructor and Description

    ByteArrayOutputStream()
    

    Creates a new byte array output stream.

    ByteArrayOutputStream(int size)
    

    Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.