public class MemoryWriter : IDisposable { long _startMem; string _text; public MemoryWriter(string text) { _text = text + " - "; _startMem = GC.GetTotalMemory(true); } public void Dispose() { Console.WriteLine("mem: " + _text + (GC.GetTotalMemory(true) - _startMem).ToString()); } } Usage looks like: using (new MemoryWriter("CrazyBigObject")) { CrazyBigObject myCrazyBigObject = LoadCrazyBigObject(42); }
/// <summary> /// Returns a rough approximation of the size of an object /// (including ALL objects in/directly referenced by the object) /// </summary> public static long ApproxSize(object obj) { BinaryFormatter formatter = new BinaryFormatter(); long length; using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, obj); stream.Seek(0, SeekOrigin.Begin); length = stream.Length; } return length; }
/// <summary>/// Returns the approximate size of very large objects /// (time intensive) in bytes./// </summary> public static long ApproxSizeLarge(object obj) { FileInfo info = new FileInfo(@"c:\approxSizeTemp"); BinaryFormatter formatter = new BinaryFormatter(); using (StreamWriter writer = new StreamWriter(@"c:\approxSizeTemp")) { formatter.Serialize(writer.BaseStream, obj); } long length = info.Length; info.Delete(); return length; }
Click Download Nitriq Now for download options on the NimblePros download page.