2

I have recently encountered a problem about the memory my program used. The reason is the memory of an array of string i used in a method. More specifically, this program is to read an integer array from a outside file. Here is my code

class Program
{

    static void Main(string[] args)
    {
        int[] a = loadData();
        for (int i = 0; i < a.Length; i++)
        {
            Console.WriteLine(a[i]);
        }
        Console.ReadKey();
    }

    private static int[] loadData()
    {
        string[] lines = System.IO.File.ReadAllLines(@"F:\data.txt");
        int[] a = new int[lines.Length];
        for (int i = 0; i < lines.Length; i++)
        {
            string[] temp = lines[i].Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
            a[i] = Convert.ToInt32(temp[0]);
        }
        return a;
    }
}

File data.txt is about 7.4 MB and 574285 lines. But when I run, the memory of program shown in task manager is : 41.6 MB. It seems that the memory of the array of string I read in loadData() (it is string[] lines) is not be freed. How can i free it, because it is never used later.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
khaimaitien
  • 51
  • 1
  • 7
  • That memory will be automatically freed up when the garbage collector runs. Furthermore, you can't determine when the garbage collector will actually run. You don't need to worry about it. – Idle_Mind Sep 21 '13 at 04:32

1 Answers1

1

You can call GC.Collect() after setting lines to null, but I suggest you look at all answers here, here and here. Calling GC.Collect() is something that you rarely want to do. The purpose of using a language such as C# is that it manages the memory for you. If you want granular control over the memory read in, then you could create a C++ dll and call into that from your C# code.

Instead of reading the entire file into a string array, you could read it line by line and perform the operations that you need to on that line. That would probably be more efficient as well.

What problem does the 40MB of used memory cause? How often do you read the data? Would it be worth caching it for future use (assuming the 7MB is tolerable).

Community
  • 1
  • 1
acarlon
  • 16,764
  • 7
  • 75
  • 94
  • I only use it one time only. – khaimaitien Sep 21 '13 at 04:41
  • @khaimaitien why not read the file line by line then and do the operations as you need to rather than reading into a string array to begin with? You can change the int[] to a list that will be more efficient and use less memory up front. Of course it is still up to the GC as to when it frees the memory. – acarlon Sep 21 '13 at 04:47
  • this is only an example, in my real program I use Dictionary class to hold a pair of string and integer. it is encouraged to use Dictionay with known capacity due to the speed. – khaimaitien Sep 21 '13 at 08:51
  • @khaimaitien, ok great, then you could read line by line into dictionary. – acarlon Sep 21 '13 at 11:16