I try to read byte array using stackalloc to reduce gc for better performance. And in 2021.2 there has complete support for Span. But when I test with BinaryReader, and find some problem. My test code is below:
using System;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine.Assertions;
public static class BinaryReaderSpan
{
[MenuItem("Test/Test BinaryReader to Span")]
private static void Test1()
{
using var stream = new MemoryStream();
using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
{
Span<byte> bytes = stackalloc byte[16];
for (int i = 0; i < 16; ++i)
{
bytes[i] = (byte)i;
}
writer.Write(bytes);
}
stream.Position = 0;
using (var reader = new BinaryReader(stream, Encoding.UTF8, true))
{
Span<byte> bytes = stackalloc byte[16];
reader.Read(bytes);
for (int i = 0; i < 16; ++i)
{
Assert.AreEqual(bytes[i], (byte)i);
}
}
}
[MenuItem("Test/Test BinaryReader to byte[]")]
private static void Test2()
{
using var stream = new MemoryStream();
using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
{
Span<byte> bytes = stackalloc byte[16];
for (int i = 0; i < 16; ++i)
{
bytes[i] = (byte)i;
}
writer.Write(bytes);
}
stream.Position = 0;
using (var reader = new BinaryReader(stream, Encoding.UTF8, true))
{
var bytes = new byte[16];
reader.Read(bytes, 0, 16);
for (int i = 0; i < 16; ++i)
{
Assert.AreEqual(bytes[i], (byte)i);
}
}
}
}
I add two menu items: ‘Test/Test BinaryReader to Span’ and ‘Test/Test BinaryReader to byte[ ]’.
‘Read to byte[ ]’ always work perfect. But ‘Read to Span’ the result always zero.
I submit a bug report for this: Case 1377375. And attach the test project.
Is it something wrong with my code? Or it is a bug for unity?
7619074–947212–ReadToSpan.zip (19.8 KB)