Deserialize makes tons of garbage

I’m using MessagePack library for this. It’s basically unity’s JSON serializer but much faster. Basically every 20ms I’m deserializing something with about 500 different entities all serialized into one object, and this, for some reason is creating absolutely tons of garbage weighing my game down.

JsonReceive = MessagePackSerializer.Deserialize<Json_ClientTickUpdate>(Message);

Here’s the command I’m running. If I remove that command, the profiler shows absolutely no issues whatsoever. Hopefully someone has some suggestions for me.

This is common with deserialization, it has to create any object(s) it needs to when deserializing.

Not sure why you would need to desterilize a json file every 20ms.

1 Like

How else is the client going to keep track of entity updates?

There has to be a way to reuse the objects.

Why are you sending json data over a network? This should be done using as small as possible amount of information and no json implementation will be able to compete with using bytes, which is the defacto standard.

I’m using the fastest library available. The only bottleneck is garbage collection.

Ps. I never said I’m using JSON. I’m using messagepack, which is basically what you described. I only mentioned JSON as an example to describe what I’m doing.

Json is for files, not to send entity data over a network during game play. Ditch json and kiss your GC problems good bye.

Sending bytes or even straight up Vector3’s will be more efficient than json for what you are trying to do, which is how pretty much all online/coop games send info to all the clients.

I’m not using json.

Sorry you mentioned json. Still using a library like MessagePacker you are stuck with how it is implemented, and with it generating garbage you would have to ask the creators if there is a way around that.

Is there any way to delete the object as soon as the script is finished with it for that tick? I think one of the main problems is that the garbage collection just keeps piling up these objects until it feels a need to delete them.

Not directly, not in a managed way that is and not without access to the underlying objects being created when deserialization happens. GC.Collect might help but is not recommended to remedy this. You can also do incremental GC which can alleviate the problem somewhat. GC in Unity is old and outdated so either generate no garbage or find a way to do it as little as possible. You are almost always better off with a custom system for sending the data you want between clients.