aboutsummaryrefslogtreecommitdiff
path: root/csharp/src/ProtocolBuffers/CodedOutputStream.cs
diff options
context:
space:
mode:
authorJon Skeet <skeet@pobox.com>2015-06-11 14:19:30 +0100
committerJon Skeet <skeet@pobox.com>2015-06-11 14:19:30 +0100
commit35e4dbd51829216fd1ad85a95c01042346b63c6b (patch)
tree0841c7e6f967bc39c0fe933aa9bc63c740f138aa /csharp/src/ProtocolBuffers/CodedOutputStream.cs
parent954e720837be515254360cf9fdf3d9681c1bd91c (diff)
downloadprotobuf-35e4dbd51829216fd1ad85a95c01042346b63c6b.tar.gz
protobuf-35e4dbd51829216fd1ad85a95c01042346b63c6b.tar.bz2
protobuf-35e4dbd51829216fd1ad85a95c01042346b63c6b.zip
Improve string encoding times.
Cache a reference to Encoding.UTF8 - the property access is (rather surprisingly) significant. Additionally, when we detect that the string is all ASCII (due to the computed length in bytes being the length in characters), we can perform the encoding very efficiently ourselves.
Diffstat (limited to 'csharp/src/ProtocolBuffers/CodedOutputStream.cs')
-rw-r--r--csharp/src/ProtocolBuffers/CodedOutputStream.cs18
1 files changed, 15 insertions, 3 deletions
diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.cs
index efc83d0e..c817a20b 100644
--- a/csharp/src/ProtocolBuffers/CodedOutputStream.cs
+++ b/csharp/src/ProtocolBuffers/CodedOutputStream.cs
@@ -58,6 +58,8 @@ namespace Google.Protobuf
/// </remarks>
public sealed partial class CodedOutputStream : ICodedOutputStream
{
+ private static readonly Encoding UTF8 = Encoding.UTF8;
+
/// <summary>
/// The buffer size used by CreateInstance(Stream).
/// </summary>
@@ -294,16 +296,26 @@ namespace Google.Protobuf
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
// Optimise the case where we have enough space to write
// the string directly to the buffer, which should be common.
- int length = Encoding.UTF8.GetByteCount(value);
+ int length = UTF8.GetByteCount(value);
WriteRawVarint32((uint) length);
if (limit - position >= length)
{
- Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, position);
+ if (length == value.Length) // Must be all ASCII...
+ {
+ for (int i = 0; i < length; i++)
+ {
+ buffer[position + i] = (byte)value[i];
+ }
+ }
+ else
+ {
+ UTF8.GetBytes(value, 0, value.Length, buffer, position);
+ }
position += length;
}
else
{
- byte[] bytes = Encoding.UTF8.GetBytes(value);
+ byte[] bytes = UTF8.GetBytes(value);
WriteRawBytes(bytes);
}
}