Dre*_*kes 1 .net c# performance stream character-encoding
我有一个流,其下N个字节是 UTF8 编码的字符串。我想以最少的开销创建该字符串。
这有效:
var bytes = new byte[n];
stream.Read(bytes, 0, n); // my actual code checks return value
var str = Encoding.UTF8.GetString(bytes);
Run Code Online (Sandbox Code Playgroud)
在我的基准测试中,我看到花费了大量时间以byte[]临时形式收集垃圾。如果我可以摆脱这些,我可以有效地将我的堆分配减半。
本UTF8Encoding类没有与流工作方法。
如果有帮助,我可以使用不安全的代码。我不能重用一个byte[]缓冲区,如果没有ThreadLocal<byte[]>它似乎引入了比它减轻的更多的开销。我确实需要支持 UTF8(ASCII 不会削减它)。
这里有我缺少的 API 或技术吗?
byte[]如果您使用可变长度的 UTF8 编码,则无法避免分配。因此,只有在读取所有这些字节后才能确定结果字符串的长度。
我们来看看UTF8Encoding.GetString方法:
public override unsafe String GetString(byte[] bytes, int index, int count)
{
// Avoid problems with empty input buffer
if (bytes.Length == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + index, count, this);
}
Run Code Online (Sandbox Code Playgroud)
它首先调用String.CreateStringFromEncoding获取结果字符串长度的方法,然后分配它并在没有额外分配的情况下用字符填充它。该UTF8Encoding.GetChars分配没有什么太。
unsafe static internal String CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
if (stringLength == 0)
return String.Empty;
String s = FastAllocateString(stringLength);
fixed (char* pTempChars = &s.m_firstChar)
{
encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您将使用固定长度编码,那么您可以直接分配一个字符串并Encoding.GetChars在其上使用。但是Stream.ReadByte多次调用会降低性能,因为没有Stream.Read接受byte*作为参数。
const int bufferSize = 256;
string str = new string('\0', n / bytesPerCharacter);
byte* bytes = stackalloc byte[bufferSize];
fixed (char* pinnedChars = str)
{
char* chars = pinnedChars;
for (int i = n; i >= 0; i -= bufferSize)
{
int byteCount = Math.Min(bufferSize, i);
int charCount = byteCount / bytesPerCharacter;
for (int j = 0; j < byteCount; ++j)
bytes[j] = (byte)stream.ReadByte();
encoding.GetChars(bytes, byteCount, chars, charCount);
chars += charCount;
}
}
Run Code Online (Sandbox Code Playgroud)
所以你已经使用了更好的方法来获取字符串。在这种情况下唯一可以做的就是实现这个ByteArrayCache类。它应该类似于StringBuilderCache.
public static class ByteArrayCache
{
[ThreadStatic]
private static byte[] cachedInstance;
private const int maxArraySize = 1024;
public static byte[] Acquire(int size)
{
if (size <= maxArraySize)
{
byte[] instance = cachedInstance;
if (cachedInstance != null && cachedInstance.Length >= size)
{
cachedInstance = null;
return instance;
}
}
return new byte[size];
}
public static void Release(byte[] array)
{
if ((array != null && array.Length <= maxArraySize) &&
(cachedInstance == null || cachedInstance.Length < array.Length))
{
cachedInstance = array;
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var bytes = ByteArrayCache.Acquire(n);
stream.Read(bytes, 0, n);
var str = Encoding.UTF8.GetString(bytes);
ByteArrayCache.Release(bytes);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1723 次 |
| 最近记录: |