【发布时间】:2023-03-27 07:15:01
【问题描述】:
我正在将文件读入byte[] buffer。该文件包含大量 UTF-16 字符串(数百万),格式如下:
- 第一个字节包含字符和字符串长度(范围 0 .. 255)
- 以下字节包含UTF-16编码的字符串字符(每个char用2个字节表示,即byteCount = charCount * 2)。
我需要对文件中的所有字符串执行标准字符串操作,例如:IndexOf、EndsWith 和StartsWith,以及StringComparison.OrdinalIgnoreCase 和StringComparison.Ordinal。
现在我的代码首先将每个字符串从字节数组转换为System.String 类型。我发现下面的代码是最有效的:
// position/length validation removed to minimize the code
string result;
byte charLength = _buffer[_bufferI++];
int byteLength = charLength * 2;
fixed (byte* pBuffer = &_buffer[_bufferI])
{
result = new string((char*)pBuffer, 0, charLength);
}
_bufferI += byteLength;
return result;
不过,new string(char*, int, int) 还是很慢,因为它执行不必要复制每个字符串。
Profiler 说它的 System.String.wstrcpy(char*,char*,int32) 执行缓慢。
我需要一种方法来执行字符串操作无需为每个字符串复制字节。
有没有办法直接对字节数组进行字符串操作?
有没有办法创建新字符串而不复制其字节?
【问题讨论】:
-
并非每个字符都编码为 UTF16 中的两个字节。
-
@Kerrek SB:确实如此,但这些字符也作为多个
char值存储在字符串中。 -
@Kerrek SB 你在谈论代码点。在 Microsoft 术语中,一个字符是 2 个字节。
标签: c# .net performance string arrays