保存3D int数组的最快方法? (XNA \ C#)

时间:2013-11-17 23:40:11

标签: c# arrays xna 2d

我需要一种快速的方法来尽快将小型3D阵列保存到文件中。 该阵列的大小为32x32x4。 我还需要一种快速读取文件的方法。

到目前为止,我已尝试循环遍历所有元素:

for (int xx = 0; xx < 32; xx += 1)
{
    for (int yy = 0; yy < 32; yy += 1)
    {
        for (int zz = 0; zz < 4; zz += 1)
        {
            String += FormatInt(array[xx, yy, zz]);
        }
    }
}

将每个整数转换为包含2位数的字符串:(上面的FormatInt()方法)

public string FormatInt(int num)
    {
        string String = "";
        String = Convert.ToString(num);
        int length = String.Length;
        for (int i = 0; i < (2 - length); i += 1)
        {
            String = String.Insert(0, "0");
        }
        return String;
    }

然后将该字符串保存为.txt文件。 然后我加载文件,然后将每个2位数的子字符串转换为整数:

int Pos = 0;
            for (int xx = 0; xx < chunkSize; xx += 1)
            {
                for (int yy = 0; yy < chunkSize; yy += 1)
                {
                    for (int zz = 0; zz < 4; zz += 1)
                    {
                        array[xx, yy, zz] = Convert.ToInt32(String.Substring(Pos * 2, 2));
                        Pos += 1;
                    }
                }
            }

我需要一种更快速的方法来保存文件。 (更快的加载也会很好,但现在它不会太慢。)

3 个答案:

答案 0 :(得分:3)

我会使用BinaryReaderBinaryWriter。您当前的方法在存储方面效率非常低,并且会出现内存问题,并使用+=添加许多字符串(请改用StringBuilder

保存:

using (BinaryWriter b = new BinaryWriter(File.Open("file.ext", FileMode.Create)))
{
    for (int xx = 0; xx < 32; xx += 1)
    {
        for (int yy = 0; yy < 32; yy += 1)
        {
            for (int zz = 0; zz < 4; zz += 1)
            {
                b.Write(array[xx, yy, zz]);
            }
        }
    }
}

装载

using (BinaryReader b = new BinaryReader(File.Open("file.ext", FileMode.Open)))
{
    for (int xx = 0; xx < 32; xx += 1)
    {
        for (int yy = 0; yy < 32; yy += 1)
        {
            for (int zz = 0; zz < 4; zz += 1)
            {
                array[xx, yy, zz] = b.ReadInt32();
            }
        }
    }
}

这比将字符串写入文件更有效,如果您的数据类型较小,则可以事件编写Int16Bytes。对于非常小的文件,您可以将它与Gzip结合使用。

答案 1 :(得分:1)

Cyral的回答是合理的。但是既然你要求尽可能快的方式,我自己的测试表明使用P / Invoke的速度提高了大约三倍:

[DllImport("kernel32.dll")]
private static extern bool WriteFile(IntPtr hFile, IntPtr lpBuffer, int nNumberOfBytesToWrite, out int lpNumberOfBytesWritten, IntPtr lpOverlapped);

private static unsafe void Write(Int32[,,] array)
{
    fixed (int* pArray = array)
    {
        using (var file = File.Open("filename", FileMode.Create, FileAccess.Write))
        {
            int written;
            WriteFile(file.SafeFileHandle.DangerousGetHandle(), (IntPtr)pArray, array.Length, out writter, IntPtr.Zero);
        }
    }
}

ReadFile()中有一个相应的kernel32.dll函数,可用于阅读,经过必要的变更

答案 2 :(得分:0)

如果你想使用字符串,那么使用StringBuilder而不是String + =因为它更有效