Over a million developers have joined DZone.

Stupid performance trick in Java

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture. Brought to you in partnership with Lightbend.

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

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O’Reilly book. Brought to you in partnership with Lightbend.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}