>
>
>
V4001. Unity Engine. Boxing inside a fr…


V4001. Unity Engine. Boxing inside a frequently called method may decrease performance.

The analyzer detected boxing inside a frequently called method. Boxing is an expensive operation that requires memory allocation in a managed heap. Thus, boxing inside a frequently called method can cause performance issues.

Here's a code example:

Vector3 _value;
....
void OnGUI()
{
  GUILayout.Label(string.Format(...., _value)); 
}

In Unity projects, the 'OnGUI' function is called for rendering a graphical user interface and handling GUI events. The function is called at least once per frame, so the code is executed frequently.

In this example, the 'string.Format' method is called, its last argument is a value type field ('Vector3'). When the method is called, the 'string.Format(string, object)' overload is used. Since an argument of the 'object' type is expected, '_value' is boxed.

We can avoid boxing if we call the 'ToString' method of the '_value' field:

Vector3 _value;
....
void OnGUI()
{
  GUILayout.Label(string.Format(...., _value.ToString()));
}

Here is another example:

struct ValueStruct { int a; int b; }

ValueStruct _previousValue;

void Update()
{
  ....
  ValueStruct newValue = ....
  ....
  if (CheckValue (newValue)
  ....
}

bool CheckValue(ValueStruct value)
{
  ....
  if(_previousValue.Equals(value))
  ....
}

The 'Update' method is widely used in Unity projects. Its code is executed every frame.

The 'CheckValue' method is called in the 'Update' method. There is implicit boxing, since 'value' is passed to the 'Equals' method (the parameter of the standard 'Equals' method is of the 'object' type).

This can be fixed by adding the 'Equals' method to the 'ValueStruct' type, the method takes in a parameter of the 'ValueStruct' type:

struct ValueStruct
{
  int a;
  int b;

  public bool Equals(ValueStruct other)
  {
    ....
  }
}

In this case, the 'CheckValue' method will use the 'Equals(ValueStruct)' overload to avoid boxing.

This diagnostic is classified as: