0

The following code to create a global variable to store the contents of a text file txt word.txt, and then create a monitor to monitor the changes in word.txt, if the content changes word.txt reset txt variable. After running the program, if I word.txt content filling 100MB, memory usage of natural increase, but then I would word.txt content to just one character, the memory footprint is not down, but will increase the number of less .

public class Program
{
public static string txt = "aaa";
static void Main()
{
    FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(@"D:\ConsoleApplication1", "word.txt");
    fileSystemWatcher.Changed += new FileSystemEventHandler(ReloadHandler);
    fileSystemWatcher.NotifyFilter = NotifyFilters.Size;
    fileSystemWatcher.EnableRaisingEvents = true;
    Console.ReadLine();
}

private static void ReloadHandler(object sender, FileSystemEventArgs e)
{
    ReloadTxtContent();
}

private static void ReloadTxtContent()
{
    txt = null;
    using ( FileStream fs = new FileStream(@"D:\ConsoleApplication1\word.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )
    {
    using ( StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default) )
    {
        txt = sr.ReadToEnd();
    }
    }
}
}

Is the global static variable assignment will repeatedly increasing memory usage? Has been cut down?

LooseLive
  • 69
  • 1
  • 8

1 Answers1

1

Firstly, strings are immutable. That means.. you're not changing the value in memory: you're creating a whole new value in memory and pointing to that.

Normally, you would assume that this immediately clears out the 100MB string you have in memory (well, not immediately.. when the Garbage Collector gets to it). However, this is not the case.

Again (as with another answer I posted earlier), this is because your 100MB string is actually allocated on the Large Object Heap. This memory isn't collected until a full garbage collection of all generations.. and it isn't compacted. Therefore, your memory usage will continue to be quite high. The CLR however, will allocate other large objects in this heap in the now empty space.

You might be interested in the following reading material:

Community
  • 1
  • 1
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • Small objects are the same – LooseLive Feb 26 '14 at 03:05
  • Yes but smaller objects are in the GC generations. They get collected _and_ compacted. The LOH doesn't get compacted.. and therefore the memory "usage" still appears high. It can be compacted in .NET 4.5 if you specify it.. but you open yourself up to performance issues during each Gen 2 collection. – Simon Whitehead Feb 26 '14 at 03:08