Use singleons for Null, Undefined, true and false BsonTokens. (#1145)

With Null and Undefined BsonValue's, one such value is
indistinguishable from another, so singletons can be used for them,
reducing allocations.

With BsonValue containing booleans as well as there being only so
there's a similar advantage with the extra benefit that if there is
only one true value then a reference-equals check can be used instead
of unboxing to determine the value to write.
This commit is contained in:
Jon Hanna
2017-01-08 09:10:10 +13:00
committed by James Newton-King
parent 218c25c859
commit ed99856139
3 changed files with 30 additions and 16 deletions
+1 -4
View File
@@ -124,10 +124,7 @@ namespace Newtonsoft.Json.Bson
}
break;
case BsonType.Boolean:
{
BsonValue value = (BsonValue)t;
_writer.Write((bool)value.Value);
}
_writer.Write(t == BsonBoolean.True);
break;
case BsonType.Null:
case BsonType.Undefined:
+25 -1
View File
@@ -87,6 +87,19 @@ namespace Newtonsoft.Json.Bson
}
}
internal class BsonEmpty : BsonToken
{
public static readonly BsonToken Null = new BsonEmpty(BsonType.Null);
public static readonly BsonToken Undefined = new BsonEmpty(BsonType.Undefined);
private BsonEmpty(BsonType type)
{
Type = type;
}
public override BsonType Type { get; }
}
internal class BsonValue : BsonToken
{
private readonly object _value;
@@ -109,10 +122,21 @@ namespace Newtonsoft.Json.Bson
}
}
internal class BsonBoolean : BsonValue
{
public static readonly BsonBoolean False = new BsonBoolean(false);
public static readonly BsonBoolean True = new BsonBoolean(true);
private BsonBoolean(bool value)
: base(value, BsonType.Boolean)
{
}
}
internal class BsonString : BsonValue
{
public int ByteCount { get; set; }
public bool IncludeLength { get; set; }
public bool IncludeLength { get; }
public BsonString(object value, bool includeLength)
: base(value, BsonType.String)
+4 -11
View File
@@ -253,7 +253,7 @@ namespace Newtonsoft.Json.Bson
public override void WriteNull()
{
base.WriteNull();
AddValue(null, BsonType.Null);
AddToken(BsonEmpty.Null);
}
/// <summary>
@@ -262,7 +262,7 @@ namespace Newtonsoft.Json.Bson
public override void WriteUndefined()
{
base.WriteUndefined();
AddValue(null, BsonType.Undefined);
AddToken(BsonEmpty.Undefined);
}
/// <summary>
@@ -272,14 +272,7 @@ namespace Newtonsoft.Json.Bson
public override void WriteValue(string value)
{
base.WriteValue(value);
if (value == null)
{
AddValue(null, BsonType.Null);
}
else
{
AddToken(new BsonString(value, true));
}
AddToken(value == null ? BsonEmpty.Null : new BsonString(value, true));
}
/// <summary>
@@ -361,7 +354,7 @@ namespace Newtonsoft.Json.Bson
public override void WriteValue(bool value)
{
base.WriteValue(value);
AddValue(value, BsonType.Boolean);
AddToken(value ? BsonBoolean.True : BsonBoolean.False);
}
/// <summary>