Skip to content

Reduce garbage allocation in SyncVar Deserialize when syncvar has no hook#4111

Open
liamcary wants to merge 1 commit intoMirrorNetworking:masterfrom
liamcary:FixAllocationInSyncVarDeserialize
Open

Reduce garbage allocation in SyncVar Deserialize when syncvar has no hook#4111
liamcary wants to merge 1 commit intoMirrorNetworking:masterfrom
liamcary:FixAllocationInSyncVarDeserialize

Conversation

@liamcary
Copy link
Copy Markdown
Contributor

While profiling my project I found that deserializing sync vars causes small allocations on the client each time the value changes. In my case I had a double and an int that was changing frequently, and each time they changed there was a 40 bytes and 32 byte allocation in GeneratedSyncVarDeserialize. There's no explicit memory allocation in GeneratedSyncVarDeserialize, but removing the Action<T, T> OnChanged parameter fixes the allocation, even though the NetworkBehaviour's DeserializeSyncVar method passes in null. I assume its a boxing operation on the generic delegate when checking if its null.

To fix the allocation, I implemented a NoHook alternative for each of the 4 GeneratedSyncVarDeserialize methods, then updated the NetworkBehaviourProcessor to call the NoHook method for SyncVar's that don't have a hook. Its not the cleanest implementation, and ideally the delegate could be passed in without any allocation, to reduce memory allocations when deserializing syncvars that DO have a hook.

This is a before and after screenshot of the profiler with Deep Profile enabled:

image

Reduces 32+ bytes of garbage allocation per deserialized syncvar when syncvar has no hook.
@liamcary
Copy link
Copy Markdown
Contributor Author

Out of curiousity, i tried an alternative approach of adding a boolean 'hasOnChange' parameter to see if the garbage allocation only happens when checking if OnChanged is null. Unfortunately it still allocates, so it seems like the presence of the Action<T, T> parameter causes allocations, whether its used or not, and whether its null or not.

image

@miwarnec
Copy link
Copy Markdown
Collaborator

miwarnec commented May 2, 2026

interesting find, gonna check this soon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants