簡體   English   中英

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

[英]Fastest Way to Save 3D int Array? (XNA \ C#)

我需要一種快速的方法來盡快將小型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;
                    }
                }
            }

我需要一種更快的方法來保存文件。 (更快的加載也會很好,但現在它不會太慢。)

我會使用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結合使用。

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);
        }
    }
}

kernel32.dll中有一個相應的ReadFile()函數,可以用於閱讀, 比照變通

如果要使用字符串,請使用StringBuilder而不是String + =,因為它更有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM