提交 0295cc78 编写于 作者: P Paul Harrington

PERF: Avoid byte[] allocations in StringHeap

上级 9a281010
......@@ -4,6 +4,7 @@
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using System.Text;
namespace Microsoft.Cci
{
......@@ -74,12 +75,17 @@ internal void WriteSbyte(sbyte value)
internal void WriteBytes(byte[] buffer)
{
if (buffer == null)
WriteBytes(buffer, 0, buffer.Length);
}
internal void WriteBytes(byte[] buffer, int offset, int count)
{
if (buffer == null || count == 0)
{
return;
}
this.BaseStream.Write(buffer, 0, buffer.Length);
this.BaseStream.Write(buffer, offset, count);
}
internal void WriteBytes(ImmutableArray<byte> buffer)
......@@ -119,7 +125,7 @@ internal void WriteChars(char[] chars)
return;
}
Debug.Assert(!_utf8, "WriteChars has a problem with unmatches surrogate pairs and does not support writing utf8");
Debug.Assert(!_utf8, "WriteChars has a problem with unmatched surrogate pairs and does not support writing utf8");
MemoryStream m = this.BaseStream;
uint i = m.Position;
......@@ -137,6 +143,29 @@ internal void WriteChars(char[] chars)
}
}
internal void WriteStringUtf16LE(string str)
{
if (str == null)
{
return;
}
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position = i + (uint)str.Length * 2;
byte[] buffer = m.Buffer;
for (int j = 0; j < str.Length; j++, i += 2)
{
char ch = str[j];
unchecked
{
buffer[i] = (byte)ch;
buffer[i + 1] = (byte)(ch >> 8);
}
}
}
internal unsafe void WriteDouble(double value)
{
MemoryStream m = this.BaseStream;
......@@ -405,6 +434,14 @@ internal void WriteString(string str, bool emitNullTerminator)
}
}
internal void WriteString(string str, Encoding encoding)
{
MemoryStream m = this.BaseStream;
uint i = m.Position;
m.Position = i + (uint)encoding.GetByteCount(str);
encoding.GetBytes(str, 0, str.Length, m.Buffer, (int)i);
}
/// <summary>
/// Implements compressed signed integer encoding as defined by ECMA-335-II chapter 23.2: Blobs and signatures.
/// </summary>
......
......@@ -208,7 +208,7 @@ public uint GetUserStringToken(string str)
index = _userStringWriter.BaseStream.Position + (uint)_userStringIndexStartOffset;
_userStringIndex.Add(str, index);
_userStringWriter.WriteCompressedUInt((uint)str.Length * 2 + 1);
_userStringWriter.WriteChars(str.ToCharArray());
_userStringWriter.WriteStringUtf16LE(str);
// Write out a trailing byte indicating if the string is really quite simple
byte stringKind = 0;
......@@ -315,10 +315,7 @@ private void SerializeStringHeap()
else
{
_stringIndexMap[cur.Value.VirtIdx] = position;
// TODO (tomat): consider reusing the buffer instead of allocating a new one for each string
_stringWriter.WriteBytes(s_utf8Encoding.GetBytes(cur.Key));
_stringWriter.WriteString(cur.Key, s_utf8Encoding);
_stringWriter.WriteByte(0);
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册