简体   繁体   中英

Out of memory exception is throwing while using Substring method in C#

i'm having a string(MyString) of length 9700000(approximately). and a for loop to get substring from this String

like

for(int i=0;i<MyString.Length;i+=1000)
  {
    String SStr=MyString.Substring(i,1000);
  }

in this loop i'm geting an exception like OutOfMemory Exception . But if i assign the MyString to a temporary string and using it( temporary string ) instead of MyString in the for loop,then its working fine. What will be the reason for this. And how its stored in memory?

EDIT : I used StringBuilder too

Like

for(int i=0;i<MyStringBuilder.Length;i+=1000)
   {
    String SStr=MyStringBuilder.ToString().Substring(i,1000);
   }

But the same thing is happening.

Edit MyString and MyStringBuilder are Global Variables

I'm not sure this loop will ever terminate.

Shouldn't it read:

for(int i=0;i<800; i+= 1000 )
{
    String SStr=MyString.Substring(i,1000);
}

So that i is increasing.

You will also want to change your upper bound (i<800)

Or perhaps what you're actually trying to do is:

for(int i=0;i<800; i++)
{
    String SStr=MyString.Substring( i * 1000 ,1000);
}

It looks like MyString might be a property which is itself creating a new string on each call.

Your 800 SubString calls will use about 2MB of memory, which is unlikely to be the problem, but if your 800 calls to MyString each allocate a new copy of your 9.7MB string, then that will be an issue.

Edit:

Answering this question is a moving target, because you keep changing it, but your new StringBuilder example calls ToString for each time around the loop, which is going to make another copy of your original string - that's going to need about 9700000 * 9700000/1000 characters of space, which although the garbage collector may come by and save you, is an awful lot of allocation work.

Your life, and everyone else's life, would be improved if you avoided using the names of classes (eg 'StringBuilder') as the names of variables. Use a different naming convention (for example, start with a lower-case letter on variables)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM