Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6617451
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T20:42:22+00:00 2026-05-25T20:42:22+00:00

I understand what immutability is, and how the String .NET class is special. The

  • 0

I understand what immutability is, and how the String .NET class is special. The immutability makes it behave like a value type even though it’s a reference type. Got it. The C# reference emphasizes this point (see string (C# Reference), emphasis added by me:

Strings are immutable–the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string “h” is then eligible for garbage collection.

Being a self-taught programmer I’m not well versed in garbage collectors and memory leaks and pointers and stuff. That’s why I’m asking a question about it. The description of how the C# compiler automatically creates new string objects and abandons old ones makes it seem like a bunch of memory could get used up with abandoned string content. A lot of objects have dispose methods or destructors so that even the automated CLR garbage collector knows when and how to clean up after an object that isn’t needed anymore. There is nothing like this for a String. I wanted to see what would actually happen if a created a program so that I could demostrate for myself and others that creating and immediately abandoning string objects can consume a lot of memory.

Here’s the program:

class Program {
    static void Main(string[] args)
    {
        Console.ReadKey();
        int megaByte = (int)Math.Pow(1024, 2);
        string[] hog = new string[2048];
        char c;
        for (int i = 0; i < 2048; i++)
        {
            c = Convert.ToChar(i);
            Console.WriteLine("Generating iteration {0} (char = '{1}')", i, c);
            hog[i] = new string(c, megaByte);
            if ((i + 1) % 256 == 0) { 
                for (int j = (i - 255); j <= i; j++) { hog[j] = hog[i]; } }
            }
        Console.ReadKey();

        List<string> uniqueStrings = new List<string>();
        for (int i = 0; i < 2048; i++) {
            if (!uniqueStrings.Contains(hog[i])) { uniqueStrings.Add(hog[i]); }
        }
        Console.WriteLine("There are {0} unique strings in hog.", uniqueStrings.Count);
        Console.ReadKey();

        // Create a timer with an interval of 30 minutes 
        // (30 minutes * 60 seconds * 1000 milliseconds)
        System.Timers.Timer t = new System.Timers.Timer(30 * 60 * 1000);
        t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
        t.Start();
        Console.WriteLine("Waiting 30 minutes...");

        Console.ReadKey();
    }

    static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("Time's up. I'm collecting the garbage.");
        GC.Collect();
    }
}

It creates a destroys bunch of unique strings and only ends up with 8 unique strings in the hog array. In my tests the process was still holding on to 570 Mb to 1.1 Gb (it varied). The timer part waits 30 minutes while leaving the process active (not sleeping) and at the end of 30 minutes, the process was still holding on to all the extra memory until I forced collection. This makes it seem like the .NET garbage collector missed something. Lots of other places people say that calling GC.Collect() is something terrible. So the fact that the memory only seems to get reclaimed by forcing the collector using this method still makes it seem like something is wrong.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T20:42:23+00:00Added an answer on May 25, 2026 at 8:42 pm

    Just that the the garbage collector of your version of the CLR reacts to memory pressure, not elapsed time. Why spend precious CPU time cleaning up memory that isn’t needed anyway?

    Sure you could argue that it would be better to perform the GC when the program is “idle”. The problem is, that you want to keep the GC algorithm as simple as possible (which usually means fast) and that the algorithm can’t read your mind. It doesn’t know when the application is doing “nothing constructive”.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I understand the difference between String and StringBuilder ( StringBuilder being mutable) but is
I understand that repr() 's purpose is to return a string, that can be
I understand that this is a reference for the caller object. I'm used to
Does string immutability work by statement, or by strings within a statement? For example,
I understand that the List<> of derived class cannot be directly assigned to List<>
I am able to understand immutability with python (surprisingly simple too). Let's say I
I understand that if else staments should say stuff like: if dog equals one,
I understand that sessions in HTTP is stateless and hence we have methods like
I understand full the ref word in the .NET Since using the same variable,
I understand the reason for having the HTML helpers in ASP.NET MVC and extending

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.