UnityEngine.Profiling.Profiler.BeginSample("SomeUniqueName");
// The code you want to profile
UnityEngine.Profiling.Profiler.EndSample();
To get a seperate sample entry in the profiler. You can easily search for that name in the profiler so you don’t need to find the frame manually and don’t need to trace the callstack manually. Once you have selected your sample you can remove the search string and your sample should be selected in the normal view.
Preventing garbage collection was introduced in NET 4.6 so depending on your Unity version, script backend and .NET version selection it may not be available to you.
So in short: No, there is no way to manually determine how much memory was allocated within a certain code section through code. And no you can’t really suppress garbage collection apart from the fact that it wouldn’t help. So you can’t incoperate memory allocation into unit tests.
Just as a side note: The System.Version class contains just 4 int values. This is 16 bytes in total. However each class instance has some additional overhead like the type pointer, vtable and maybe some memory alignment. At least in my tests one Version instance requires 32bytes of memory.
About your first example: Yes, Mono has some bad habits / implementations here. In normal .NET the default comparer actually creates a proper generic comparer (based on IEquatable<T>
) to get a garbage free comparison. Mono has several of these poor implementations (same goes for foreach and IDisposable for struct enumerators). Though this is implementation dependent behaviour that you can’t catch with unit tests in the editor properly.
edit Note that the problem with struct enumerators has been resolved in current versions, so this should no longer be an issue.
This is a pretty old thread, but for those folks arriving here from search, it turns out that Unity has since evolved the ability to write tests on allocations.
First, TestFramework contains an assertion called AllocatingGCMemory that you can use for unit tests.
Second, if you don’t use TestFramework or just want to have this functionality outside of tests, here is a utility class that uses the same technique:
gist.github.com
AllocCounter.cs
using System;
using UnityEngine.Profiling;
// Borrowed directly from UnityEngine.TestTools.Constraints.AllocatingGCMemoryConstraint
public class AllocCounter {
private Recorder _rec;
public AllocCounter() {
_rec = Recorder.Get("GC.Alloc");
This file has been truncated. show original