Reputation: 20468
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
Upvotes: 1
Views: 6656
Reputation: 1
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
Upvotes: 0
Reputation: 164
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.
Upvotes: 3
Reputation: 6698
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.
Upvotes: 0
Reputation: 16636
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.
Upvotes: 1
Reputation: 12053
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
Upvotes: 0