In Unity, should we avoid string literals in frequently executed methods (like Update()
) to avoid unnecessary memory allocations and instead store string values into fields?
class TouchInputManager : MonoBehaviour
{
// private const string messageVar = "OnFingerMove";
/* ... */
private void HandleFingerMove(Finger finger)
{
/* ... */
gameObj.SendMessage("OnFingerMove");
// vs.
// gameObj.SendMessage(messageVar);
}
}
I assume that the string literal "OnFingerMove" will allocate new memory on every frame. Will the compiler somehow optimize string literals to reduce garbage? I read some articles that suggest avoiding string concatenation in methods executed on every frame, so I started wondering if string literals would also create garbage in the heap.