Skip to content

Avoid usage of Debug.Log methods in performance critical context

Matt Ellis edited this page Feb 21, 2019 · 4 revisions

Calls to the various different Debug.Log, Debug.LogFormat, Debug.LogError, etc. methods can be very expensive and should be avoided inside a performance critical context.

Logging can be disabled by setting the ILogger.logEnabled property of the unityLogger default instance to false:

Debug.unityLogger.logEnabled = false;

or filtered by setting the ILogger.filterLogType property:

Debug.unityLogger.filterLogType = LogType.Warning;

Note that any calculations performed while evaluating the arguments to the log method, such as string concatenation, or boxing of parameters to object in calls to Debug.LogFormat, will still happen, even if the log itself is disabled or filtered.

Calls to Debug.Log methods are not disabled in release builds, and will still execute when the player is running on a device. It is possible to selectively log only inside a debug build by checking the Debug.isDebugBuild property:

if (Debug.isDebugBuild) {
  Debug.Log("This is a debug build");
}

Another alternative is to create a facade class that uses the [Conditional("…")] attribute to tell the compiler to remove calls in production builds. See the answers to this post on Unity's Answers forums for more details, especially this answer, which describes the use of the [Conditional] attribute.

This inspection will add a performance indicator to all calls to the family of Debug.Log methods inside a performance critical context. It will also mark the calling method as expensive, and any usages of the calling method will also receive a performance indicator highlight.

This inspection was first added in Rider/ReSharper 2018.3

Clone this wiki locally