Do not use ByteArrayOutputStream in performance critical code
Very important: you will rarely need
ByteArrayOutputStream in performance critical code. If you still think you may need it – read the rest of the article.
ByteArrayOutputStream is mostly used when you write a method which writes some sort of message with unknown length to some output stream (are there many cases when you can’t calculate size of your message?).
Important: if you know your message size in advance (or at least know an upper limit for it) – allocate a
ByteBuffer instead (or reuse a previously allocated one) and write a message into it. It works faster than
ByteArrayOutputStream (read Various methods of binary serialization in Java article).
ByteArrayOutputStream allows you to write anything to an internal expandable byte array and use that array as a single piece of output afterwards. Default buffer size is 32 bytes, so if you expect to write something longer, provide an explicit buffer size in the
In most cases
ByteArrayOutputStream is used either when you are writing a callback method and caller provides you with some
OutputStream, which nature is undefined, or if you are writing some “message to byte array” serialization method. Second case is covered in Various methods of binary serialization in Java article.
From above mentioned article you will know that
ByteArrayOutputStream is synchronized and it seriously impacts its performance. So, if you don’t need synchronization, go to JDK sources, copy class contents to your project and remove all synchronization from it (and forget that it was my advice! 🙂 ). This will make it a bit faster…