创建具有大容量的StringBuilder

时间:2012-05-02 22:34:19

标签: vb.net stringbuilder

我在老板的项目中找到了以下代码:

Dim strBuilder As New System.Text.StringBuilder("", 1000000)

在我打电话给他之前,我想确认这行是否实际上为那个字符串构建器设置了一兆字节(或两兆字节的Unicode?)内存?

2 个答案:

答案 0 :(得分:3)

初始化长度为1000000的Char()

因此内存中所需的实际大小为 2000000字节 = ~2 MB,因为char是unicode并且需要2个字节。

编辑:万一你的老板不相信,ILSpy反映了这一点:

// System.Text.StringBuilder
[SecuritySafeCritical]
public unsafe StringBuilder(string value, int startIndex, int length, int capacity)
{
    if (capacity < 0)
    {
        throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", new object[]
        {
            "capacity"
        }));
    }
    if (length < 0)
    {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", new object[]
        {
            "length"
        }));
    }
    if (startIndex < 0)
    {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
    }
    if (value == null)
    {
        value = string.Empty;
    }
    if (startIndex > value.Length - length)
    {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
    }
    this.m_MaxCapacity = 2147483647;
    if (capacity == 0)
    {
        capacity = 16;
    }
    if (capacity < length)
    {
        capacity = length;
    }
    this.m_ChunkChars = new char[capacity];
    this.m_ChunkLength = length;
    fixed (char* ptr = value)
    {
        StringBuilder.ThreadSafeCopy(ptr + (IntPtr)startIndex, this.m_ChunkChars, 0, length);
    }
}

答案 1 :(得分:1)

您可以尝试在分配之前和之后调用GC.GetTotalMemory(),看看它是否会增加。注意:这不是一个好的,科学的方法,但可以证明你的观点。