I was unable to find anything that expressly answered my question so I thought I would ask: Is it best practice or just preference to do something like:
public static class FixedStrings
{
public static readonly string foo = "bar";
}
class Example1
{
void UseString()
{
Console.WriteLine(FixedStrings.foo);
}
}
Instead of:
class Example2
{
void UseString()
{
Console.WriteLine("bar");
}
}
This is my current understanding (I could be wrong):
- It is a trade-off of memory vs GC allocations; so the first example is the better choice if the method requiring the string is called often, or it is in a long running process.
- If memory is not an issue, caching strings (or any objects) that can be reused will reduce time the GC takes and increase responsiveness of program.
- The .NET GC does a pretty good job, but periodically a couple of those strings will get through the generations especially if under load and after a long time may cause full GC cleanup.
Example1
beatsExample2
pretty much always in terms of performance.
I noticed in example code from various places, people use both. I am unsure if it is just because example2
is quicker to type or if because of reading preference. I am also curious, is the compiler smart enough to automatically turn some of these strings into cached variables?
Please keep in mind I say all of this with just what I have learned from the internet, I have no formal education. I may be very wrong about assuming example1
is better
Here is why I worry about such a minor optimization:
It is not so minor in my actual project; in some cases I may be using these strings thousands of times per second.