Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET const affecting compiled assembly size

Why are const usages replaced by their values on compile time but then still included in the assembly? At least this is what IL DASM and Reflector shows.

Currently I am using const for defining many magic numbers and strings to easier be able to change code without affecting run-time performance.

Now I know that that doesnt affect the used memory but it still affects compiled assembly size which is crucial for example for mobile phone apps.

Another disadvantage is that other people easier understand magic numbers when looking at the disassembled code.

I am really interested in why the compiler (Mono as well as .NET) does this exactly?

like image 943
stfx Avatar asked Feb 16 '23 21:02

stfx


1 Answers

This behaviour is specified in the ECMA-335 standard (of which both .NET and Mono are implementations). Citing from section II.22.9, "Constant":

Note that Constant information does not directly influence runtime behavior, although it is visible via Reflection (and hence can be used to implement functionality such as that provided by System.Enum.ToString). Compilers inspect this information, at compile time, when importing metadata, but the value of the constant itself, if used, becomes embedded into the CIL stream the compiler emits. There are no CIL instructions to access the Constant table at runtime.

That is, const values are "inlined" (possibly because they can be, and for performance reasons), but are kept in metadata nevertheless so they can be inspected by compilers and tools.

If no metadata were emitted for the const-ness of fields, this would have these consequences (possibly among others — these are just two examples):

  • Compilers or tools like Reflector could no longer distinguish between regular fields and const fields.
  • If you inspected a field using System.Reflection, you would no longer be able to use the FieldInfo.IsLiteral property.
like image 146
stakx - no longer contributing Avatar answered Mar 25 '23 00:03

stakx - no longer contributing