简体   繁体   English

在C#中使用Substring方法时抛出内存不足异常

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

i'm having a string(MyString) of length 9700000(approximately). 我有一个长度为9700000(大约)的字符串(MyString)。 and a for loop to get substring from this String 和for循环以从此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 . 在此循环中,我遇到了OutOfMemory Exception类的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. 但是,如果我在指定MyString到一个临时字符串,并使用它( temporary string ),而不是MyString的for循环,那么它的工作的罚款。 What will be the reason for this. 这是什么原因。 And how its stored in memory? 以及它如何存储在内存中?

EDIT : I used StringBuilder too 编辑 :我也使用StringBuilder

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 编辑 MyString和MyStringBuilder是全局变量

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. 因此, i正在增加。

You will also want to change your upper bound (i<800) 您还需要更改上限(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. 看起来MyString可能是一个属性,它本身在每次调用时都会创建一个新字符串。

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. 您的800个SubString调用将使用大约2MB的内存,这不太可能出现问题,但是,如果您对MyString的800个调用每个都分配了9.7MB字符串的新副本,那么这将是一个问题。

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. 回答这个问题是一个移动的目标,因为您不断更改它,但是新的StringBuilder示例在循环中每次都调用ToString,这将为您的原始字符串制作另一个副本-大约需要9700000 * 9700000/1000尽管垃圾收集器可能会派上用场并为您节省空间,但这些字符却是很多分配工作。

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. 如果避免使用类的名称(例如“ StringBuilder”)作为变量的名称,将会改善您的生活以及其他所有人的生活。 Use a different naming convention (for example, start with a lower-case letter on variables) 使用其他命名约定(例如,以小写字母开头的变量)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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