Performance Zone is brought to you in partnership with:

Peter is a DZone MVB and is not an employee of DZone and has posted 142 posts at DZone. You can read more from them at their website. View Full User Profile

Stupid performance trick in Java

11.28.2011
| 5087 views |
  • submit to reddit
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

Published at DZone with permission of Peter Lawrey, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

John David replied on Wed, 2012/01/25 - 7:09pm

Also another way to improve your java performance is to specify you buffer size at the start and hard code it in your code according to your requirements.

also keep in mind the memory size of your deployment server or machine.

new java

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.