Over a million developers have joined DZone.

Stupid performance trick in Java

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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.flip();
     out.write(buf);
     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)
        bb.clear();
    else
        bb.compact();
}

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

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}