Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Readonly Fields and Performance

Tags:

c#

memory

Let's say I have a class that has many fields that are initialized with data from a configuration file. Resharper et. al. often recommend applying the static readonly modifiers.

My understanding is that the static keyword causes the variable to be stored in the stack as opposed to the heap. So I started to wonder if there are memory usage implications with having a lot of static fields. I searched around, and the best I could find was this article on static strings that says (emphasis mine):

When you use the static keyword on a string, you indicate that you only need one string reference, which can point to only one object. If you have many string values in your program, don't choose the static keyword.

But unfortunately it doesn't explain why.

So my best guess at this point is that you get a performance bump from using the static modifier because there is a pointer involved, but you shouldn't use them liberally, because it could put pressure on memory as the garbage collector will never sweep them up?

Is that accurate?

like image 982
personaelit Avatar asked Mar 14 '23 22:03

personaelit


1 Answers

Shoot. That's a really poorly written article.

Basically what they're trying to get at is a relatively simple concept: when you use the static keyword you only get one variable, whereas when you omit it, you get one variable per instance. The variable is static, not the string.

As far as memory storage for strings, all strings are stored on the heap, never on the stack. The only strings that have special storage are called interned strings, which are a whole different can of worms and not at all applicable to this question.

As for your last comment, strings with long lifetimes are a completely normal thing that the GC knows how to deal with, they get moved into a corner that doesn't affect performance very much once they've survived for a while without being deleted.

like image 67
Kyle Sletten Avatar answered Mar 23 '23 17:03

Kyle Sletten