improve memory consumption in write path

This change will reduce the overhead of buffers in write path.
The goal is to consume less memory and do less copying of byte arrays.
ByteArrayOutputStream would copy the whole buffer when it becomes too small.
I also included logic to reduce the number of times we check if we reached the page size.
Which should improve write performance.