diff options
author | Jon Skeet <skeet@pobox.com> | 2015-06-19 08:38:21 +0100 |
---|---|---|
committer | Jon Skeet <skeet@pobox.com> | 2015-06-19 08:38:21 +0100 |
commit | d7dda2fed8c37a83e2d4cd7ecc4201b628588c4c (patch) | |
tree | 57c7f96b86492fa2090730fc86ff15b3745f3814 /csharp | |
parent | a0f956932df52ead0223a68243b5862c7b037cf1 (diff) |
Use an empty array instead of a null reference for an empty repeated field.
Diffstat (limited to 'csharp')
-rw-r--r-- | csharp/src/ProtocolBuffers/Collections/RepeatedField.cs | 32 |
1 files changed, 10 insertions, 22 deletions
diff --git a/csharp/src/ProtocolBuffers/Collections/RepeatedField.cs b/csharp/src/ProtocolBuffers/Collections/RepeatedField.cs index 0cd5cf80..25651784 100644 --- a/csharp/src/ProtocolBuffers/Collections/RepeatedField.cs +++ b/csharp/src/ProtocolBuffers/Collections/RepeatedField.cs @@ -6,25 +6,21 @@ namespace Google.Protobuf.Collections { public sealed class RepeatedField<T> : IList<T>, IEquatable<RepeatedField<T>> { + private static readonly T[] EmptyArray = new T[0]; + private const int MinArraySize = 8; - private T[] array = null; + private T[] array = EmptyArray; private int count = 0; private void EnsureSize(int size) { - if (array == null) - { - array = new T[Math.Max(size, MinArraySize)]; - } - else + size = Math.Max(size, MinArraySize); + if (array.Length < size) { - if (array.Length < size) - { - int newSize = Math.Max(array.Length * 2, size); - var tmp = new T[newSize]; - Array.Copy(array, 0, tmp, 0, array.Length); - array = tmp; - } + int newSize = Math.Max(array.Length * 2, size); + var tmp = new T[newSize]; + Array.Copy(array, 0, tmp, 0, array.Length); + array = tmp; } } @@ -51,7 +47,7 @@ namespace Google.Protobuf.Collections public void Clear() { - array = null; + array = EmptyArray; count = 0; } @@ -62,10 +58,6 @@ namespace Google.Protobuf.Collections public void CopyTo(T[] array, int arrayIndex) { - if (this.array == null) - { - return; - } Array.Copy(this.array, 0, array, arrayIndex, count); } @@ -183,10 +175,6 @@ namespace Google.Protobuf.Collections { throw new ArgumentNullException("item"); } - if (array == null) - { - return -1; - } // TODO(jonskeet): Does this box for enums? EqualityComparer<T> comparer = EqualityComparer<T>.Default; for (int i = 0; i < count; i++) |