Ordinarily, retrieving a string
property from an object is the same as retrieving any other reference type property in C#; it should be acquired with no additional memory cost. However, retrieving string
properties from GameObjects
is another subtle way of accidentally crossing over the Native-Managed Bridge.
The two properties of GameObject
affected by this behavior are tag
and name
. Therefore, it is unwise to use either properties during gameplay, and you should only use them in performance-inconsequential areas, such as Editor Scripts. However, the Tag System is commonly used for runtime identification of objects, which can make this a significant problem for some teams.
For example, the following code would cause an additional memory allocation during every iteration of the loop:
for (int i = 0; i < listOfObjects.Count; ++i) { if (listOfObjects[i].tag == "Player") { // do something with this object } }
It is often a better practice...