1

I want to fill a list like below :

    List<string> list_lines = new List<string>();
    for (double num = double.Parse(txtStart.Text); num < 99999999; num++)
    {
        list_lines.Add(num.ToString());
    }

but those codes cause error at 33,554,432 and that error :
Out Of Memory Exception
I want to work with that list, what is the replacement of that or how can i fix that error?

thanks in advance

SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • On my system I run out of memory at `33,554,432`; tried it with double and int and with or without parsing, but it stops at the exact same iteration in all cases. – John Willemse Apr 09 '13 at 06:39
  • dear jhon, i test it with int. still have same error. – SilverLight Apr 09 '13 at 06:40
  • Yes, me too, that's what I wrote. The only thing that gives you more room is to drop the .ToString() and put the values in a list of ints instead of strings. However, you will still run out of memory with these kind of numbers. – John Willemse Apr 09 '13 at 06:42
  • what should i do, i need those numbers! – SilverLight Apr 09 '13 at 06:43
  • What is it that you're actually trying to achieve? There are a lot of different answers, but they depend on what you're trying to actually do. – Corey Apr 09 '13 at 06:47
  • Compile code for x64 =) – xtmq Nov 07 '13 at 07:51

5 Answers5

3

If you can replace List with IEnumerable than you can use following approach

    static IEnumerable<string> Gen()
    {
        for (double num = 0; num < 99999999; num++)
        {
            yield return num.ToString();
        }
    }

So basically you do not allocate memory, with further processing you have to keep in mind that you cannot call something like Gen().ToArray() this will produce the same issue. If you need list there is no way this will work.

1

You can do some memory optimizations, e.g. only doing the parsing once:

var parsed_number = double.Parse(txtStart.Text);

List<string> list_lines = new List<string>();
for (double num = parsed_number; num < 99999999; ++num)
{
    list_lines.Add(num.ToString());
}

That might help with the memory usage.

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
0

You don't have enough memory!
Each step of loop reserve memory. Whole loop need [99999999 * 99999999/2 * sizeof(double)] B. This is really big number

Jacek
  • 11,661
  • 23
  • 69
  • 123
0

If you need the numbers, try this code instead:

int startNumber = int.Parse(txtStart.Text);
List<int> list_lines = new List<int>();

for (int i = startNumber; i < 99999999; i++)
{
    list_lines.Add(i);
}

That will run without problems. If you need the numbers as a string later, just convert them at the moment you retrieve them.

John Willemse
  • 6,608
  • 7
  • 31
  • 45
0

I suggest John Willemse's answer - ints are faster than strings anytime..

Just convert to string when required - check out this link for the best possible method (of conversion) for your scenario:

Better way to cast object to int

Community
  • 1
  • 1