google / flatbuffers

FlatBuffers: Memory Efficient Serialization Library
https://flatbuffers.dev/
Apache License 2.0
23.28k stars 3.25k forks source link

Need Some Guide For Flat Buffer in Java #4352

Closed ztkmkoo closed 7 years ago

ztkmkoo commented 7 years ago

Hi~

I'm a new User of Flat Buffer. And New User for Java. I Have Some problem in it and Need your guide. (For 1.6 Release)

1. FlatBufferBuilder

It was allowed to Generate packet byte with FlatbufferBuilder. To use the FlatBufferBuilder, i have to allocate a new FlatBufferBuilder. and it works to allocate like below.

static ByteBuffer newByteBuffer(int capacity) { ByteBuffer newbb = ByteBuffer.allocate(capacity); //Here Allocate From Heap Memory newbb.order(ByteOrder.LITTLE_ENDIAN); return newbb; }

If i code like Example Code: FlatBufferBuilder fbb = new FlatBufferBuilder(1);

I would new some Heap Memory And Finally it would activate Garbage Collector? Its the First Question. So I Have to Use this With Object Pool? Or I can pass my pooled Memory Buffer to FlatbufferBuilder?

2. Load Packet.

In the Java Guide, it told me to use the Method getRootAsMessage() to Get the object Message. But in the Generated Code(Class, Generated From Flatc.exe --java) It seems like allocate New Object(From Heap Memory) and Mapping this Object variable From the Message Buffer. See the Blows.

public static Message getRootAsMessage(ByteBuffer _bb) { return getRootAsMessage(_bb, new Message()); }

public static Message getRootAsMessage(ByteBuffer _bb, Message obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }

But in Your C++ Code inline const MyGame::Sample::Monster GetMonster(const void buf) { return flatbuffers::GetRoot(buf); } It Seems to return the Just Binary Data..

Is it a bug or something else?

aardappel commented 7 years ago
  1. Just use FlatBufferBuilder. It has a clear method that you can use to reset it and reuse it, thereby reducing GC usage. You should not have to deal with calling newByteBuffer unless you want to.

  2. In C++ you can point a class at pre-existing data, in Java you can't. But notice the second way of calling it, you can supply your own Message rather than relying on the generated code to call new. This way, you can reuse the Message object many times and reduce GC.

ztkmkoo commented 7 years ago

Thanks you~

I Understand Java cannot work like c++. If I have the better way, i'll try to make a branch~