Stupid performance trick in Java
Join the DZone community and get the full member experience.
Join For Free
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
Topics:
Opinions expressed by DZone contributors are their own.
Comments