I have a java class that writes small messages (< 100 bytes) to a buffer. I have three message types, and so I've allocated 3 buffers.
// Cache seprate buffers for each message type
Class MyWriter(){
private ByteBuffer loginBuffer = ByteBuffer.allocate(35);
private ByteBuffer registerBuffer = ByteBuffer.allocate(23);
private ByteBuffer placeOrderBuffer = ByteBuffer.allocate(75);
....
}
And then I reuse them on new writes. For example:
private void writeLogin(){
loginBuffer.clear();
loginBuffer.putLong(...)
...
}
private void writeRegister(){
writeBuffer.clear();
writeBuffer.putLong(...)
...
}
I profiled my application and this class is where most processing time is spent.
I had initially thought it would be more efficient to allocate the buffers once, and then run the .clear()
method, instead of allocating a new buffer on each read. However, while this is certainly more memory-efficient, does the buffer.clear()
method take more CPU time, as it has to find the buffer's place in memory?
**My question is: ** would it actually be a better design to allocate on-the-fly? IE:
private void writeLogin(){
loginBuffer = ByteBuffer.allocate(35)
loginBuffer.putLong(...)
...
}
Sure, it would waste more memory, but if it speeds up the processing time, that's great. Is there a rule of thumb, or has anyone already thought about this?
I'm new to Java and not sure how to test something simple like this.