Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method containing object instances, is it wrong?

I'm using an extension method for string class. Within that extension method I create an instance of StringBuilder.

Here is the code:

    public static string GetPlainTextFromHtml(this string htmlString)
    {
        StringBuilder sb = new StringBuilder();
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(htmlString);

        foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()"))
        {
            string text = node.InnerText;
            if (!string.IsNullOrEmpty(text))
                sb.Append(text.Trim());
        }

        return sb.ToString();
    }

It works but I have a concern regarding memory management. Static methods don't get instantiated, so what happens if I instantiate an object within static method. Let's say I call this static method 100 times, would there be 100 copies of StringBuilder instances in memory?

Would it cause memory leak? Does Garbage Collector disposes object instance when static method execution terminated?

like image 252
Bogac Avatar asked Oct 30 '14 14:10

Bogac


3 Answers

If you call the static method 100 times, each time it will create the StringBuilder, perform the work in the method and then return. Once the method is executed and returned, your StringBuilder is out of scope and is left for the garbage collector to clean up. So, yes, if you call the method 100 times there will be 100 instances of the StringBuilder created - but each one of them will be disposed of and garbage collected.

like image 119
Dave Zych Avatar answered Oct 18 '22 09:10

Dave Zych


There's absolutely nothing wrong with your code.

Creating instances inside of a static method works the same way as creating instances inside of an instance method. Each call will generate a new instance but will fall out of scope and ready for garbage collection at the end of the method call.

I also don't see anything that implements IDisposable so you don't need to worry about cleaning up after yourself there either.

like image 42
Justin Niessner Avatar answered Oct 18 '22 08:10

Justin Niessner


Yes, it is perfectly ok to instantiate objects inside static methods. They live within the scope of the method, i.e. when the method returns, they will be marked to be garbage collected (unless you assign them to a field of the parameter or another static field). Yes, for every call to the method, it will instantiate those objects, and that's really what you want it to do; otherwise, multithreading such a method would be a PITA.

If you want to recycle an object, you need to have another static field accessible from the static method that holds the reference. If you use multithreading, at this point you are potentially sharing resources and need to take precautions.

like image 44
Janis F Avatar answered Oct 18 '22 10:10

Janis F