Over a million developers have joined DZone.

Stupid performance trick in Java

DZone 's Guide to

Stupid performance trick in Java

· Java Zone ·
Free Resource
ByteBuffer has a compact() method which is useful for re-using a buffer if it is not full consumed. However, in the likely case it is consumed, it can perform surprising badly.


while (in.read(buf) >= 0 || buf.position != 0) {
     buf.compact();    // In case of partial write

In my application, the throughput increased by 6% by replacing compact() with this method.


public static void compact(ByteBuffer bb) {
    if (bb.remaining() == 0)

Note: this is not the increase in a micro-benchmark, but across the entire application!

Your Mileage May Vary of course


From http://vanillajava.blogspot.com/2011/11/stupid-performance-trick-in-java.html


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}