V4004. Unity Engine. New array object is returned from method or property. Using such member in performance-sensitive context can lead to decreased performance.
The PVS-Studio analyzer has detected that the frequently executed code contains accesses to properties or methods. These properties or methods create a new array.
All Unity APIs that return arrays create a new collection each time they are accessed. This causes memory allocation in a managed heap. If we access these properties and methods often, this can lead to decreased performance.
Take a look at this example:
void Update()
{
for (int i = 0; i < Camera.allCameras.Length; i++)
{
SetDepth(Camera.allCameras[i].depth);
SetName(Camera.allCameras[i].name);
SetMask(Camera.allCameras[i].eventMask);
....
}
}
Values are written in the 'Update' method. These values correspond to a specific camera. This method is called for each frame. When the 'Camera.allCameras' property is accessed, a new array is created. As a result, a new collection will be created four times on each 'for' iteration (once when checking the loop condition, three times in the body).
We can avoid multiple creation of new collections, if we get the 'Camera.allCameras' value before the loop:
void Update()
{
var cameras = Camera.allCameras;
for (int i = 0; i < cameras.Length; i++)
{
SetDepth(cameras[i].depth);
SetName(cameras[i].name);
SetMask(cameras[i].eventMask);
....
}
}
In this case, 'Camera.allCameras' is accessed once. The value of this property is assigned to the 'cameras' variable. Later, this variable is used instead of the 'Camera.allCameras' property to write camera parameters.
Take a look at another example:
void Update()
{
SetNecessaryGameObjectParameters();
}
void SetNecessaryGameObjectParameters()
{
for (int i = 0; i < GameObject.FindGameObjectsWithTag("Enemy").Length; i++)
{
SetName(GameObject.FindGameObjectsWithTag("Enemy")[i].name);
SetTag(GameObject.FindGameObjectsWithTag("Enemy")[i].tag);
....
}
}
The information about the objects of the 'GameObject' type is written to the 'SetNecessaryGameObjectParameters' method. We get these objects via calling the 'GameObject.FindGameObjectsWithTag' method. Each time this method is called, a new collection is created. 'SetNecessaryGameObjectParameters' is used in the 'Update' method, which is a frequently called method.
If we want to avoid creating new collections, we can take the method call out of the loop:
void Update()
{
SetNecessaryGameObjectParameters();
}
void SetNecessaryGameObjectParameters()
{
var enemies = GameObject.FindGameObjectsWithTag("Enemy");
for (int i = 0; i < enemies.Length; i++)
{
SetName(enemies[i].name);
SetTag(enemies[i].tag);
....
}
}
Now 'GameObject.FindGameObjectsWithTag' is called once. The return value of this method is written into the 'enemies' variable. Further, we get information about the objects of the 'GameObject' type with the help of this variable, instead of calling 'GameObject.FindGameObjectsWithTag'.