-2

I am trying to use ByteBuffer as an internal storage for a class. I want to abstract the flip() and ByteBuffer manipulation from the caller but also do not want to use slice() as it creates additional garbage.

Is there any alternative or design suggestions?

phts
  • 3,889
  • 1
  • 19
  • 31
  • Can you clarify more details about how you want to slice up the `ByteBuffer`? If you're retaining the top-level `ByteBuffer`, that's not actually any extra garbage. – Louis Wasserman Jan 11 '16 at 20:09
  • Say I have a class : Class X { ByteBuffer get(){ return temp.slice(); } void set(ByteBuffer in){ temp.clear(); //Copy temp.flip() } } How can I rewrite get such that I don’t create garbage, And not handing the caller a byte buffer that the caller need to flip – user5775299 Jan 11 '16 at 20:32

1 Answers1

0

Assuming you're running on hotspot and as long as the lifetime of the slice is very shortlived, e.g. immediately used in the method creating it or by its caller, then escape analysis should be able to eliminate that allocation.

That is a JVM optimization, so there's no guarantee that it happens, but it generally is good enough to not worry about those things.

Also, young GCs are very efficient. The cost of such short-lived objects is very low, even if EA does not kick in.

Also, you should avoid premature optimizations. Worry about such things once you measured performance and figured out where the actual bottlenecks are.

the8472
  • 40,999
  • 5
  • 70
  • 122