Don't allocate memory in Update loops on iOS. - How strictly should this be followed?

I read in the manual that its best to avoid memory allocations in Update functions. I understand what this means generally, don't create new textures every update, don't instantiate objects every update. But I wonder how intensely must you adhere to this?

Like for example I tend to do alot of

Vector3 newPos = transform.position; newPos.y += Time.deltaTime; transform.position = newPos

Should I not be doing something like that in update? Should I make like a temporary 'globalUtilityVector3' outside of the update loop, so then I don't have to create any temporary Vector3's to read in and out data?

I also do alot of

GUI.TintColor = new Color(1,1,1,.5);

should I not do that either? Should I declare a 'globalUtilityColor' outside of Update and then go

globalUtilityColor.a = .5; GUI.TinColor = globalUtilityColor;

?

Actually, the Vector3 and globalUtilityColor won’t do anything to your memory allocation. Since they are stack allocated, you will see zero memory allocation from them.

Rule of thumb:

  • It is ok to allocate structs such as Vector3 in your functions. They won’t add any memory consumption.
  • Don’t allocate any classes such as Transform during a function.

I would say if you are debating creating a struct locally, DO IT. It will give you cleaner code. Looking at a long list of global variables that are only used inside of one specific function will confuse anyone who looks at your code.

Hi,

You could/should store newPos , Color infos, etc in variables yes, and that would avoid creating it on each update. I don't know what kind of standard you should follow to write them but I use something like `_newPos_` or `_tintColor_` and I then know that them variable are simply here to avoid memory allocation and really do not hold anything relevant.

EDIT: It seems that this is not important after all given all the comments, but without a proper bold statement from Unity in their docs ( haven't find one, but willing to learn!), I still prefer avoiding creating new variables inside function, when the function is called a lot during your game loop most likely). It might be unnecessary, yes, but I feel better like that with my current experience.

Bye,

Jean