C#的StringBuilder OutOfMemoryException异常 [英] C# Stringbuilder OutOfMemoryException

查看:1429
本文介绍了C#的StringBuilder OutOfMemoryException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了下面的函数

public void TestSB()
{
  string str = "The quick brown fox jumps over the lazy dog.";
  StringBuilder sb = new StringBuilder();
  int j = 0;
  int len = 0;

  try
  {
     for (int i = 0; i < (10000000 * 2); i++)
     {
        j = i;
        len = sb.Length;
        sb.Append(str);
     }

    Console.WriteLine("Success ::" + sb.Length.ToString());
  }
  catch (Exception ex)
  {
      Console.WriteLine(
          ex.Message + " :: " + j.ToString() + " :: " + len.ToString());
  }
}

现在我想,那StringBuilder的已采取的能力超过2十亿字符(2,147,483,647要准确)。

Now I suppose, that stringbuilder has the capacity to take over 2 billion character (2,147,483,647 to be precise).

但是,当我跑这给了的System.OutOfMemoryException只是达到约800亿容量的上述功能。
此外,我看到在不同的PC机广泛不同的结果具有相同的内存和负载的类似数额。

But when i ran the above function it gave "System.OutOfMemoryException" just on reaching the capacity of about 800 million. Moreover, I am seeing widely different result on different pc having same memory and similar amount of load.

任何人都可以请提供或解释我这样做的原因。

Can anyone please provide or explain me the reason for this.

推荐答案

每个字符需要2个字节(作为字符在.NET中是UTF-16编码单元)。所以,你的时间已经达到了800万字,这是1.6GB的的连续的内存要求 1 。现在,当StringBuilder的需要来调整自己,它创造的其他的数组新的大小(我相信尝试将容量提高一倍)的 - 这意味着试图分配一个3.2GB阵列

Each character requires 2 bytes (as a char in .NET is a UTF-16 code unit). So by the time you've reached 800 million characters, that's 1.6GB of contiguous memory required1. Now when the StringBuilder needs to resize itself, it has to create another array of the new size (which I believe tries to double the capacity) - which means trying to allocate a 3.2GB array.

我的认为的是,CLR(即使在64位系统)的大小不能拨出超过2GB的单个对象。 (这当然曾经是这样的。)我的猜测是,你的的StringBuilder 正试图在规模上翻一番,吹这个限制。您可以通过构建以获得高一点的的StringBuilder 与特定的能力 - 围绕一个十亿的可能的可行能力

I believe that the CLR (even on 64-bit systems) can't allocate a single object of more than 2GB in size. (That certainly used to be the case.) My guess is that your StringBuilder is trying to double in size, and blowing that limit. You may be able to get a little higher by constructing the StringBuilder with a specific capacity - a capacity of around a billion may be feasible.

在事物的这种正常过程是没有问题的,当然 - 甚至需要数百兆的是罕见的字符串

In the normal course of things this isn't a problem, of course - even strings requiring hundreds of megs are rare.

1 我相信实施的StringBuilder 在.NET 4中使用的片段实际改变在某些情况下 - 但我不知道的细节。所以它可能不会的总是的需要连续的内存,同时仍然在建设者的形式...但它如果你曾经叫的ToString

1 I believe the implementation of StringBuilder actually changed in .NET 4 to use fragments in some situations - but I don't know the details. So it may not always need contiguous memory while still in builder form... but it would if you ever called ToString.

这篇关于C#的StringBuilder OutOfMemoryException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆