开发者

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


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 (e.g. 'StringBuilder') as the names of variables. Use a different naming convention (for example, start with a lower-case letter on 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜