>
>
>
V4005. Unity Engine. The expensive oper…


V4005. Unity Engine. The expensive operation is performed inside 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 expensive properties or methods.

According to the Unity documentation, when some methods and properties from the Unity API are accessed, they perform expensive operations. If we access these properties and methods frequently, this can lead to decreased performance.

Take a look at this example:

public void Update()
{
  foreach (var cameraHandler in CameraHandlers)
  {
    cameraHandler(Camera.main);
  }

  ....
}

The camera is handled in the 'Update' method. This method is called for each frame. When the 'Camera.main' property is accessed, a cache lookup is performed, which overloads a CPU. As a result, the expensive operation is performed on each loop iteration.

We can avoid accessing the 'Camera.main' property multiple times by writing its value into a variable.

public void Update()
{
  var camera = Camera.main;

  foreach (var cameraHandler in CameraHandlers)
  {
    cameraHandler(camera);
  }

  ....
}

In this case, 'Camera.main' is accessed once. The value of this property is assigned to the 'camera' variable. Then this variable is used instead of the 'Camera.main' property to handle the camera.

Take a look at another example:

public void Update()
{
  ProcessCamera();

  ....
}

private void ProcessCamera()
{
  if (GetComponent<Camera>() == null)
    return;

  var cameraDepth = GetComponent<Camera>().depth;
  var cameraName = GetComponent<Camera>().name;
  var cameraEvent = GetComponent<Camera>().eventMask;
}

The information about the camera is written to the 'ProcessCamera' method. We get the camera by calling 'GetComponent<Camera>'. This method searches for the object of the 'Camera' type. This operation is expensive. Each time the 'ProcessCamera' method is called, the 'GetComponent<Camera>' method is executed four times. 'ProcessCamera' is used in the 'Update' method, which is a frequently called method.

If we want to avoid multiple execution of the expensive operation, we can write the result of 'GetComponent<Camera>' to the variable.

private void ProcessCamera()
{
  var camera = GetComponent<Camera>();

  if (camera == null)
    return;

  var cameraDepth = camera.depth;
  var cameraName = camera.name;
  var cameraEvent = camera.eventMask;

  ....
}

Now 'GetComponent<Camera>' is called once. The return value of this method is written to the 'camera' variable. Further, we get information about the camera with the help of this variable instead of calling 'GetComponent<Camera>'.