Marek
Marek

Reputation: 10402

CLR: What is the lifetime of const string values in memory?

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).

Upvotes: 4

Views: 1456

Answers (3)

Guffa
Guffa

Reputation: 700552

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).

Upvotes: 0

Adrian Zanescu
Adrian Zanescu

Reputation: 8008

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

Upvotes: 0

Brian Rasmussen
Brian Rasmussen

Reputation: 116421

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.

Upvotes: 3

Related Questions