简体   繁体   中英

Do static properties cause memory bloat?

This may be a micro-optimization, but I'm just curious to learn some background on how .NET handles these different approaches.

private const string SomeText = "(imagine this might be pages worth of text)"
public static ObjectThing SomeObject { get; } = new ObjectThing(SomeText);

vs

public static ObjectThing GetSomeObject() {
    const string someText = "(kilobytes or megabytes of text)";
    return new ObjectThing(someText);
}

Using a string probably isn't the best example; it's just what I was working with when I started wondering this.

Generally speaking, my thought is that the second approach lives and dies by the garbage collector.

But that makes me wonder: if you initialize enough static properties, and if they're large enough, does it have a relatively negative impact on the overall program?

does it have a relatively negative impact on the overall program?

Static properties are implemented using static fields which are GC roots. Therefore, any object reachable from a static property will live forever.

It is possible to cause too much memory usage that way for sure. It's just another way of causing heap usage like any other.

Whether it is too much or not depends on the amount of memory used, the amount of memory available and whether GC speed is a bottleneck or not.

In practical applications this usually does not matter. Except of course if you are anchoring a huge data structure there but again that has nothing to do with being referenced a static property. It's just general memory usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM