Question: ByteBuffer vs MemorySegment for binary (de)serializiation and in-memory buffer pool

Michael Zucchi notzed at gmail.com
Wed Aug 24 00:34:31 UTC 2022


On 23/8/22 03:57, Gavin Ray wrote:
> Thanks Paul,
>
> The API is a fair bit wordier, but that's the price you pay in 
> exchange for greater expressiveness and flexibility I suppose.
> I'll likely go forward with the MemorySegment implementation then -- I 
> appreciate the reply!
>
TBH it probably wont turn out to be wordier once you get it worked out.  
ByteBuffer was better than nothing but MemorySegment is cleaner for 
memory access as it doesn't carry the nio baggage.  And some of the 
boilerplate better encapsulates various operations you would need to 
perform separately anyway.

Also one doesn't need to do any deserialisation for many types of 
accesses since you can just access the memory directly via varhandles.  
If the data is not packed but naturally aligned and ordered then 
accessing it via var handles into primitive types is simple and more 
efficient than marshalling to another object first.

e.g.
  in C, 'slot[i].offset' could become 
'slot$offset$varhandle.get(segment, i)' which you through in an accessor 
on some object like Page which holds the segment.

where the varhandle is something like

static VarHandle slot$offset$varhandle = 
slotLAYOUT.sequenceLayout().varHandle(
         MemoryLayout.PathElement.sequenceElement(),
         MemoryLayout.PathElement.groupElement("offset"));

  !Z



More information about the panama-dev mailing list