views:

75

answers:

3

Say we have a class with 10000 const string members.

class Schema
{
  //Average string length is 20
  public const string ID1 = "some.constant.value";
  public const string ID2 = "some.other.constant.value";
  //...
}

Not all fields are referenced in the rest of the code. Only 10% of them is accessed on startup - their reference is assigned as a key to various dictionaries (thousands of Dictionary instances). I understand that const strings are interned - referencing a const string multiple times does not increase consumed memory by more than the size of the metadata token pointing to an offset in the interned string table.

I understand that the const strings are compiled into the assembly and thus influence the size of the compiled assembly.


At what exact time/event do these const strings consume runtime memory?

Will be all the memory needed for all the const strings taken at the time the assembly is loaded or is this delayed until the class is JIT compiled?

Can we decrease memory consumption after startup by changing something in the equation? (make the fields non-const, make the strings static fields?).

Let's assume a Winforms application (.NET 2.0).

+3  A: 

Const strings are compile time literals, and since the CLR uses interning for these they will stick around for as long as the application is alive.

You may also find my answer to this question relevant.

Brian Rasmussen
A: 

I may be wrong but when the assembly is first referenced it is loaded entirely in memory with all the code, metadata and constant values (i don't know for sure if embedded resources are loaded also or deferred). And it will remain loaded until the process is terminated

AZ
@Henk I get that. But the question is what does it load on demand. The whole assembly (my take) or just bits of it?
AZ
Just the bits it needs.
Henk Holterman
A: 

It doesn't matter that the strings are constants. The constants themselves doesn't take up any memory at all, it's the literal strings that take up memory.

When you use the constants in your code, the compiler will substitute it for a reference to the literal string.

The string literals are loaded with the assembly, so they stick around throughout the life time of the application. Even if you change your constants to something else, the string literals are still there. Using variables instead of constants will actually use more memory, because it needs somewhere to store the value of the variable (i.e. a copy of the reference to the literal string).

Guffa
So you are suggesting that if I do not use any of the constants in the code, no memory will be taken by them?
Marek
@Marek: The literal strings will still take up memory, the compiler can't optimise them away. The constants (i.e. references to the literal strings) are declarations used at compile time, they never take up any memory.
Guffa