Determine C # code size

I would like to check how big the compiled code of some classes (in bytes) is. I would like to optimize them in size, but I need to know where to start.

+5
source share
3 answers

If you want to know the size in bytes needed to store the class / type at runtime.

For value types, use sizeof(type); for reference types , use sizeoffor each field / property.


If you want to know the size of the managed DLLs, the obvious way is to compile the dll and check the file size. To do this programmatically, take a look at user1027167 answer and CodeDomProviderclass.

- , , - IL , sizeof (, ) .

MethodBase.GetMethodBody.

Roslyn ( ) ( ) , , , ( , IL.


, DLL, - Reflector

+3

- MSIL Reflection. MSIL , . , , Debug versus Release.

using System.Reflection;

int totalSize = 0;

foreach(var mi in typeof(Example).GetMethods(BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.Static | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty))
{
  MethodInfo mi = typeof(Example).GetMethod("MethodBodyExample");
  MethodBody mb = mi.GetMethodBody();
  totalSize += mb.GetILAsByteArray().Length;
}
+3

Assuming you want to know the size in bytes of your compiled code, I think you need to compile it. If you want to automate it, look at this:

ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString());
if (cr.Errors.HasErrors)
{
    StringBuilder error = new StringBuilder();
    error.Append("Error Compiling Expression: ");
    foreach (CompilerError err in cr.Errors)
    {
        error.AppendFormat("{0}\n", err.ErrorText);
    }
    throw new Exception("Error Compiling Expression: " + error.ToString());
}
Assembly a = cr.CompiledAssembly;

The variable "code" (here is its StringBuilder) must contain the actual source code of your class that you want to measure. After compilation, you only need to see what size the output assembly has.

+1
source

All Articles