ScriptableObject-Architecture icon indicating copy to clipboard operation
ScriptableObject-Architecture copied to clipboard

Setting value for FloatVariable is causing GC allocations and slower execution

Open SharkWithLasers opened this issue 4 years ago • 4 comments

In one of my MonoBehaviours, I am updating a FloatVariable every Update.

However, I am noticing that this is causing the Update for the function to be much slower than if I had just set a float.

With the line myFloatVariable.Value = myFloat, the Update function takes 0.54ms to complete and has a bunch of GC allocations: image

Setting only the float itself is significantly less time: image

Anyone know why this might be the case?

Thanks!

SharkWithLasers avatar Aug 19 '21 05:08 SharkWithLasers

It's because every time you assign a FloatVariable, the variable iterates over all listeners listening to that variable assignation and invoke an event in case it should. That's why it takes much more time to assign a FloatVariable than a float.

chulini avatar Aug 19 '21 08:08 chulini

Ahh, that makes sense. I didn't expect FloatVariable to inherit from GameEventBase. I'm not sure if it's wise to update a FloatVariable every frame of an update loop.

I also noticed that the GC allocations happen because "enable debug" is on in Preferences. Turning off "enable debug" gets rid of most of the allocations, and gave comparable performance to using FloatVariable with debug on.

SharkWithLasers avatar Aug 23 '21 06:08 SharkWithLasers

I had one time the bad idea of setting the player's input every frame on a couple of FloatVariable and, as I added more and more listeners for those variables, everything started gradually to becoming very slow.

My advise would be not to use SO when you need something to be updated every frame.

chulini avatar Aug 23 '21 10:08 chulini

The GC allocations are probably coming from GameEventBase's StackTrace feature. These allocations only happen in the Editor.

Monsoonexe avatar Oct 04 '21 09:10 Monsoonexe