-Changed perf tests to BenchmarkDotNet

This commit is contained in:
James Newton-King
2017-02-26 10:59:14 +13:00
parent ce04999633
commit 69638744f8
25 changed files with 1708 additions and 1826 deletions
+3 -181
View File
@@ -24,16 +24,9 @@
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests;
using Newtonsoft.Json.Tests.Converters;
using BenchmarkDotNet.Running;
using Newtonsoft.Json.Tests.Benchmarks;
namespace Newtonsoft.Json.TestConsole
{
@@ -41,181 +34,10 @@ namespace Newtonsoft.Json.TestConsole
{
public static void Main(string[] args)
{
Console.WriteLine("Json.NET Test Console");
string version = FileVersionInfo.GetVersionInfo(typeof(JsonConvert).Assembly.Location).FileVersion;
Console.WriteLine("Json.NET Version: " + version);
Console.ReadKey();
Console.WriteLine("Doing stuff...");
//PerformanceTests t = new PerformanceTests();
//t.DeserializeLargeJson();
//PerformanceTests t = new PerformanceTests();
TokenWriteToAsync();
//t.Iterations = 50000;
//t.BenchmarkDeserializeMethod<TestClass>(PerformanceTests.SerializeMethod.JsonNet, PerformanceTests.JsonText);
//Console.WriteLine("Wait to do stuff again");
//Console.ReadKey();
//t.BenchmarkDeserializeMethod<TestClass>(PerformanceTests.SerializeMethod.JsonNet, PerformanceTests.JsonText);
//ReadLargeJson();
//WriteLargeJson();
//DeserializeJson();
//ReadLargeJson();
//ReadLargeJsonJavaScriptSerializer();
Console.WriteLine();
Console.WriteLine("Finished");
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
public static void LargeArrayJTokenPathPerformance()
{
JArray a = new JArray();
for (int i = 0; i < 100000; i++)
{
a.Add(i);
}
JToken last = a.Last;
int interations = 1000;
Console.WriteLine("Ready!!!");
Console.ReadKey();
string p = null;
for (int i = 0; i < interations; i++)
{
p = last.Path;
}
}
public static void TokenWriteToAsync()
{
PerformanceTests t = new PerformanceTests();
t.Iterations = 50000;
t.TokenWriteToAsync().Wait();
}
public static void SerializeJsonAsync()
{
PerformanceTests t = new PerformanceTests();
t.Iterations = 50000;
t.SerializeAsync().Wait();
}
public static void DeserializeJsonAsync()
{
PerformanceTests t = new PerformanceTests();
t.Iterations = 50000;
t.DeserializeAsync().Wait();
}
public static void DeserializeJson()
{
PerformanceTests t = new PerformanceTests();
t.Iterations = 50000;
t.Deserialize();
}
public static void DeserializeLargeJson()
{
PerformanceTests t = new PerformanceTests();
t.DeserializeLargeJson();
}
public static void WriteLargeJson()
{
var json = System.IO.File.ReadAllText("large.json");
IList<PerformanceTests.RootObject> o = JsonConvert.DeserializeObject<IList<PerformanceTests.RootObject>>(json);
Console.WriteLine("Press any key to start serialize");
Console.ReadKey();
Console.WriteLine("Serializing...");
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10; i++)
{
using (StreamWriter file = System.IO.File.CreateText("largewrite.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
serializer.Serialize(file, o);
}
}
sw.Stop();
Console.WriteLine("Finished. Total seconds: " + sw.Elapsed.TotalSeconds);
}
public static void ReadLargeJson()
{
using (var jsonFile = System.IO.File.OpenText("large.json"))
using (JsonTextReader jsonTextReader = new JsonTextReader(jsonFile))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Deserialize<IList<PerformanceTests.RootObject>>(jsonTextReader);
}
Console.WriteLine("Press any key to start deserialization");
Console.ReadKey();
Console.WriteLine("Deserializing...");
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 5; i++)
{
using (var jsonFile = System.IO.File.OpenText("large.json"))
using (JsonTextReader jsonTextReader = new JsonTextReader(jsonFile))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Deserialize<IList<PerformanceTests.RootObject>>(jsonTextReader);
}
}
sw.Stop();
Console.WriteLine("Finished. Total seconds: " + sw.Elapsed.TotalSeconds);
}
public static void ReadLargeJsonJavaScriptSerializer()
{
string json = System.IO.File.ReadAllText("large.json");
JavaScriptSerializer s = new JavaScriptSerializer();
s.MaxJsonLength = int.MaxValue;
s.Deserialize<IList<PerformanceTests.RootObject>>(json);
Console.WriteLine("Press any key to start deserialization");
Console.ReadKey();
Console.WriteLine("Deserializing...");
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 5; i++)
{
json = System.IO.File.ReadAllText("large.json");
s = new JavaScriptSerializer();
s.MaxJsonLength = int.MaxValue;
s.Deserialize<IList<PerformanceTests.RootObject>>(json);
}
sw.Stop();
Console.WriteLine("Finished. Total seconds: " + sw.Elapsed.TotalSeconds);
new BenchmarkSwitcher(new [] { typeof(SerializeBenchmarks), typeof(DeserializeBenchmarks) }).Run(new[] { "*" });
}
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,80 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class DeserializeBenchmarks
{
private static readonly string LargeJsonText;
private static readonly string FloatArrayJson;
static DeserializeBenchmarks()
{
LargeJsonText = System.IO.File.ReadAllText("large.json");
FloatArrayJson = new JArray(Enumerable.Range(0, 5000).Select(i => i * 1.1m)).ToString(Formatting.None);
}
[Benchmark]
public IList<RootObject> DeserializeLargeJsonText()
{
return JsonConvert.DeserializeObject<IList<RootObject>>(LargeJsonText);
}
[Benchmark]
public IList<RootObject> DeserializeLargeJsonFile()
{
using (var jsonFile = System.IO.File.OpenText("large.json"))
using (JsonTextReader jsonTextReader = new JsonTextReader(jsonFile))
{
JsonSerializer serializer = new JsonSerializer();
return serializer.Deserialize<IList<RootObject>>(jsonTextReader);
}
}
[Benchmark]
public IList<double> DeserializeDoubleList()
{
return JsonConvert.DeserializeObject<IList<double>>(FloatArrayJson);
}
[Benchmark]
public IList<decimal> DeserializeDecimalList()
{
return JsonConvert.DeserializeObject<IList<decimal>>(FloatArrayJson);
}
}
}
@@ -0,0 +1,323 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class DeserializeComparisonBenchmarks
{
private static readonly byte[] BinaryFormatterData = TestFixtureBase.HexToBytes(BenchmarkConstants.BinaryFormatterHex);
private static readonly byte[] BsonData = TestFixtureBase.HexToBytes(BenchmarkConstants.BsonHex);
[Benchmark]
public TestClass DataContractSerializer()
{
return DeserializeDataContract<TestClass>(BenchmarkConstants.XmlText);
}
private T DeserializeDataContract<T>(string xml)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
return (T)serializer.ReadObject(ms);
}
private T DeserializeDataContractJson<T>(string json)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
return (T)dataContractSerializer.ReadObject(ms);
}
[Benchmark]
public TestClass BinaryFormatter()
{
return DeserializeBinaryFormatter<TestClass>(BinaryFormatterData);
}
private T DeserializeBinaryFormatter<T>(byte[] bytes)
{
BinaryFormatter formatter = new BinaryFormatter();
return (T)formatter.Deserialize(new MemoryStream(bytes));
}
[Benchmark]
public TestClass JavaScriptSerializer()
{
return DeserializeWebExtensions<TestClass>(BenchmarkConstants.JsonText);
}
public T DeserializeWebExtensions<T>(string json)
{
JavaScriptSerializer ser = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
return ser.Deserialize<T>(json);
}
[Benchmark]
public TestClass DataContractJsonSerializer()
{
return DeserializeDataContractJson<TestClass>(BenchmarkConstants.JsonText);
}
[Benchmark]
public TestClass JsonNet()
{
return JsonConvert.DeserializeObject<TestClass>(BenchmarkConstants.JsonText);
}
[Benchmark]
public TestClass JsonNetIso()
{
return JsonConvert.DeserializeObject<TestClass>(BenchmarkConstants.JsonIsoText);
}
[Benchmark]
public TestClass JsonNetManual()
{
return DeserializeJsonNetManual(BenchmarkConstants.JsonText);
}
#region DeserializeJsonNetManual
private TestClass DeserializeJsonNetManual(string json)
{
TestClass c = new TestClass();
JsonTextReader reader = new JsonTextReader(new StringReader(json));
reader.Read();
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = (string)reader.Value;
switch (propertyName)
{
case "strings":
reader.Read();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
c.strings.Add((string)reader.Value);
}
break;
case "dictionary":
reader.Read();
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
string key = (string)reader.Value;
c.dictionary.Add(key, reader.ReadAsInt32().GetValueOrDefault());
}
break;
case "Name":
c.Name = reader.ReadAsString();
break;
case "Now":
c.Now = reader.ReadAsDateTime().GetValueOrDefault();
break;
case "BigNumber":
c.BigNumber = reader.ReadAsDecimal().GetValueOrDefault();
break;
case "Address1":
reader.Read();
c.Address1 = CreateAddress(reader);
break;
case "Addresses":
reader.Read();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
var address = CreateAddress(reader);
c.Addresses.Add(address);
}
break;
}
}
else
{
break;
}
}
return c;
}
private static Address CreateAddress(JsonTextReader reader)
{
Address a = new Address();
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
{
switch ((string)reader.Value)
{
case "Street":
a.Street = reader.ReadAsString();
break;
case "Phone":
a.Phone = reader.ReadAsString();
break;
case "Entered":
a.Entered = reader.ReadAsDateTime().GetValueOrDefault();
break;
}
}
else
{
break;
}
}
return a;
}
#endregion
[Benchmark]
public Task<TestClass> JsonNetManualAsync()
{
return DeserializeJsonNetManualAsync(BenchmarkConstants.JsonText);
}
[Benchmark]
public Task<TestClass> JsonNetManualIndentedAsync()
{
return DeserializeJsonNetManualAsync(BenchmarkConstants.JsonIndentedText);
}
private async Task<TestClass> DeserializeJsonNetManualAsync(string json)
{
TestClass c = new TestClass();
JsonTextReader reader = new JsonTextReader(new StringReader(json));
await reader.ReadAsync();
while (await reader.ReadAsync())
{
if (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = (string)reader.Value;
switch (propertyName)
{
case "strings":
await reader.ReadAsync();
while (await reader.ReadAsync() && reader.TokenType != JsonToken.EndArray)
{
c.strings.Add((string)reader.Value);
}
break;
case "dictionary":
await reader.ReadAsync();
while (await reader.ReadAsync() && reader.TokenType != JsonToken.EndObject)
{
string key = (string)reader.Value;
c.dictionary.Add(key, (await reader.ReadAsInt32Async()).GetValueOrDefault());
}
break;
case "Name":
c.Name = await reader.ReadAsStringAsync();
break;
case "Now":
c.Now = (await reader.ReadAsDateTimeAsync()).GetValueOrDefault();
break;
case "BigNumber":
c.BigNumber = (await reader.ReadAsDecimalAsync()).GetValueOrDefault();
break;
case "Address1":
await reader.ReadAsync();
c.Address1 = await CreateAddressAsync(reader);
break;
case "Addresses":
await reader.ReadAsync();
while (await reader.ReadAsync() && reader.TokenType != JsonToken.EndArray)
{
var address = await CreateAddressAsync(reader);
c.Addresses.Add(address);
}
break;
}
}
else
{
break;
}
}
return c;
}
private static async Task<Address> CreateAddressAsync(JsonTextReader reader)
{
Address a = new Address();
while (await reader.ReadAsync())
{
if (reader.TokenType == JsonToken.PropertyName)
{
switch ((string)reader.Value)
{
case "Street":
a.Street = await reader.ReadAsStringAsync();
break;
case "Phone":
a.Phone = await reader.ReadAsStringAsync();
break;
case "Entered":
a.Entered = (await reader.ReadAsDateTimeAsync()).GetValueOrDefault();
break;
}
}
else
{
break;
}
}
return a;
}
#pragma warning disable 618
[Benchmark]
public TestClass JsonNetBson()
{
return DeserializeJsonNetBson<TestClass>(BsonData);
}
private T DeserializeJsonNetBson<T>(byte[] bson)
{
JsonSerializer serializer = new JsonSerializer();
return (T)serializer.Deserialize(new BsonReader(new MemoryStream(bson)), typeof(T));
}
#pragma warning restore 618
}
}
@@ -0,0 +1,97 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class JTokenBenchmarks
{
private static readonly JObject JObjectSample = JObject.Parse(BenchmarkConstants.JsonText);
private static readonly string JsonTextSample;
private static readonly string NestedJsonText;
static JTokenBenchmarks()
{
JObject o = new JObject();
for (int i = 0; i < 50; i++)
{
o[i.ToString()] = i;
}
JsonTextSample = o.ToString();
NestedJsonText = (new string('[', 100000)) + "1" + (new string(']', 100000));
}
[Benchmark]
public void TokenWriteTo()
{
StringWriter sw = new StringWriter();
JObjectSample.WriteTo(new JsonTextWriter(sw));
}
[Benchmark]
public Task TokenWriteToAsync()
{
StringWriter sw = new StringWriter();
return JObjectSample.WriteToAsync(new JsonTextWriter(sw));
}
[Benchmark]
public JObject JObjectParse()
{
return JObject.Parse(JsonTextSample);
}
[Benchmark]
public JArray JArrayNestedParse()
{
return JArray.Parse(NestedJsonText);
}
[Benchmark]
public JArray JArrayNestedBuild()
{
JArray current = new JArray();
JArray root = current;
for (int j = 0; j < 100000; j++)
{
JArray temp = new JArray();
current.Add(temp);
current = temp;
}
current.Add(1);
return root;
}
}
}
@@ -0,0 +1,64 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class JValueConvertBenchmarks
{
private static readonly JValue StringJValue = new JValue("String!");
[Benchmark]
public string JTokenToObjectFast()
{
return (string)StringJValue.ToObject(typeof(string));
}
[Benchmark]
public string JTokenToObjectWithSerializer()
{
return (string)StringJValue.ToObject(typeof(string), new JsonSerializer());
}
[Benchmark]
public string JTokenToObjectConvert()
{
return StringJValue.Value<string>();
}
[Benchmark]
public string JTokenToObjectCast()
{
return (string)StringJValue;
}
}
}
@@ -0,0 +1,68 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.IO;
using System.Linq;
using System.Xml;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class JsonTextReaderBenchmarks
{
private static readonly string FloatArrayJson;
static JsonTextReaderBenchmarks()
{
FloatArrayJson = new JArray(Enumerable.Range(0, 5000).Select(i => i * 1.1m)).ToString(Formatting.None);
}
[Benchmark]
public void ReadLargeJson()
{
using (StreamReader fs = System.IO.File.OpenText("large.json"))
using (JsonTextReader jsonTextReader = new JsonTextReader(fs))
{
while (jsonTextReader.Read())
{
}
}
}
[Benchmark]
public void ReadAsDecimal()
{
using (JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(FloatArrayJson)))
{
jsonTextReader.Read();
while (jsonTextReader.ReadAsDecimal() != null)
{
}
}
}
}
}
@@ -0,0 +1,47 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.IO;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class JsonTextWriterBenchmarks
{
private static readonly string UnicodeCharsString = (new string('\0', 30));
[Benchmark]
public string SerializeUnicodeChars()
{
StringWriter sw = new StringWriter();
JsonTextWriter jsonTextWriter = new JsonTextWriter(sw);
jsonTextWriter.WriteValue(UnicodeCharsString);
jsonTextWriter.Flush();
return sw.ToString();
}
}
}
@@ -0,0 +1,74 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class LargeJArrayBenchmarks
{
private JArray _largeJArraySample;
[Setup]
public void SetupData()
{
_largeJArraySample = new JArray();
for (int i = 0; i < 100000; i++)
{
_largeJArraySample.Add(i);
}
}
[Benchmark]
public string JTokenPathFirstItem()
{
JToken first = _largeJArraySample.First;
return first.Path;
}
[Benchmark]
public string JTokenPathLastItem()
{
JToken last = _largeJArraySample.Last;
return last.Path;
}
[Benchmark]
public void AddPerformance()
{
_largeJArraySample.Add(1);
_largeJArraySample.RemoveAt(_largeJArraySample.Count - 1);
}
}
}
@@ -0,0 +1,89 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class LowLevelBenchmarks
{
private const string FloatText = "123.123";
private static readonly char[] FloatChars = FloatText.ToCharArray();
[Benchmark]
public void DecimalTryParseString()
{
decimal value;
decimal.TryParse(FloatText, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value);
}
[Benchmark]
public void DecimalTryParseChars()
{
decimal value;
ConvertUtils.DecimalTryParse(FloatChars, 0, FloatChars.Length, out value);
}
[Benchmark]
public void WriteEscapedJavaScriptString()
{
string text = @"The general form of an HTML element is therefore: <tag attribute1=""value1"" attribute2=""value2"">content</tag>.
Some HTML elements are defined as empty elements and take the form <tag attribute1=""value1"" attribute2=""value2"" >.
Empty elements may enclose no content, for instance, the BR tag or the inline IMG tag.
The name of an HTML element is the name used in the tags.
Note that the end tag's name is preceded by a slash character, ""/"", and that in empty elements the end tag is neither required nor allowed.
If attributes are not mentioned, default values are used in each case.
The general form of an HTML element is therefore: <tag attribute1=""value1"" attribute2=""value2"">content</tag>.
Some HTML elements are defined as empty elements and take the form <tag attribute1=""value1"" attribute2=""value2"" >.
Empty elements may enclose no content, for instance, the BR tag or the inline IMG tag.
The name of an HTML element is the name used in the tags.
Note that the end tag's name is preceded by a slash character, ""/"", and that in empty elements the end tag is neither required nor allowed.
If attributes are not mentioned, default values are used in each case.
The general form of an HTML element is therefore: <tag attribute1=""value1"" attribute2=""value2"">content</tag>.
Some HTML elements are defined as empty elements and take the form <tag attribute1=""value1"" attribute2=""value2"" >.
Empty elements may enclose no content, for instance, the BR tag or the inline IMG tag.
The name of an HTML element is the name used in the tags.
Note that the end tag's name is preceded by a slash character, ""/"", and that in empty elements the end tag is neither required nor allowed.
If attributes are not mentioned, default values are used in each case.
";
using (StringWriter w = StringUtils.CreateStringWriter(text.Length))
{
char[] buffer = null;
JavaScriptUtils.WriteEscapedJavaScriptString(w, text, '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
}
}
}
}
@@ -0,0 +1,54 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using BenchmarkDotNet.Running;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests.Benchmarks
{
[TestFixture]
public class Runner : TestFixtureBase
{
[Test]
[Ignore("Don't run with other unit tests")]
public void RunBenchmarks()
{
new BenchmarkSwitcher(typeof(Runner).GetTypeInfo().Assembly).Run(new []{ "*" });
}
}
}
@@ -0,0 +1,62 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class SerializeBenchmarks
{
private static readonly IList<RootObject> LargeCollection;
static SerializeBenchmarks()
{
string json = System.IO.File.ReadAllText("large.json");
LargeCollection = JsonConvert.DeserializeObject<IList<RootObject>>(json);
}
[Benchmark]
public void SerializeLargeJsonFile()
{
using (StreamWriter file = System.IO.File.CreateText("largewrite.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
serializer.Serialize(file, LargeCollection);
}
}
}
}
@@ -0,0 +1,331 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class SerializeComparisonBenchmarks
{
private static readonly TestClass TestClass = CreateSerializationObject();
private static TestClass CreateSerializationObject()
{
TestClass test = new TestClass();
test.dictionary = new Dictionary<string, int> { { "Val & asd1", 1 }, { "Val2 & asd1", 3 }, { "Val3 & asd1", 4 } };
test.Address1.Street = "fff Street";
test.Address1.Entered = DateTime.Now.AddDays(20);
test.BigNumber = 34123123123.121M;
test.Now = DateTime.Now.AddHours(1);
test.strings = new List<string>() { null, "Markus egger ]><[, (2nd)", null };
Address address = new Address();
address.Entered = DateTime.Now.AddDays(-1);
address.Street = "\u001farray\u003caddress";
test.Addresses.Add(address);
address = new Address();
address.Entered = DateTime.Now.AddDays(-2);
address.Street = "array 2 address";
test.Addresses.Add(address);
return test;
}
[Benchmark]
public string DataContractSerializer()
{
return SerializeDataContract(TestClass);
}
private string SerializeDataContract(object value)
{
DataContractSerializer dataContractSerializer = new DataContractSerializer(value.GetType());
MemoryStream ms = new MemoryStream();
dataContractSerializer.WriteObject(ms, value);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
[Benchmark]
public byte[] BinaryFormatter()
{
return SerializeBinaryFormatter(TestClass);
}
private byte[] SerializeBinaryFormatter(object value)
{
MemoryStream ms = new MemoryStream(Buffer);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, value);
return ms.ToArray();
}
[Benchmark]
public string JavaScriptSerializer()
{
return SerializeWebExtensions(TestClass);
}
private string SerializeWebExtensions(object value)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(value);
}
[Benchmark]
public string DataContractJsonSerializer()
{
return SerializeDataContractJson(TestClass);
}
public string SerializeDataContractJson(object value)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(value.GetType());
MemoryStream ms = new MemoryStream();
dataContractSerializer.WriteObject(ms, value);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
[Benchmark]
public string JsonNet()
{
return JsonConvert.SerializeObject(TestClass);
}
[Benchmark]
public string JsonNetLinq()
{
return SerializeJsonNetLinq(TestClass);
}
#region SerializeJsonNetManual
private string SerializeJsonNetLinq(TestClass c)
{
JObject o = new JObject(
new JProperty("strings", new JArray(c.strings)),
new JProperty("dictionary", new JObject(c.dictionary.Select(d => new JProperty(d.Key, d.Value)))),
new JProperty("Name", c.Name),
new JProperty("Now", c.Now),
new JProperty("BigNumber", c.BigNumber),
new JProperty("Address1", new JObject(
new JProperty("Street", c.Address1.Street),
new JProperty("Phone", c.Address1.Phone),
new JProperty("Entered", c.Address1.Entered))),
new JProperty("Addresses", new JArray(c.Addresses.Select(a =>
new JObject(
new JProperty("Street", a.Street),
new JProperty("Phone", a.Phone),
new JProperty("Entered", a.Entered)))))
);
return o.ToString(Formatting.None);
}
#endregion
[Benchmark]
public string JsonNetManual()
{
return SerializeJsonNetManual(TestClass);
}
#region SerializeJsonNetManual
private string SerializeJsonNetManual(TestClass c)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("strings");
writer.WriteStartArray();
foreach (string s in c.strings)
{
writer.WriteValue(s);
}
writer.WriteEndArray();
writer.WritePropertyName("dictionary");
writer.WriteStartObject();
foreach (KeyValuePair<string, int> keyValuePair in c.dictionary)
{
writer.WritePropertyName(keyValuePair.Key);
writer.WriteValue(keyValuePair.Value);
}
writer.WriteEndObject();
writer.WritePropertyName("Name");
writer.WriteValue(c.Name);
writer.WritePropertyName("Now");
writer.WriteValue(c.Now);
writer.WritePropertyName("BigNumber");
writer.WriteValue(c.BigNumber);
writer.WritePropertyName("Address1");
writer.WriteStartObject();
writer.WritePropertyName("Street");
writer.WriteValue(c.BigNumber);
writer.WritePropertyName("Street");
writer.WriteValue(c.BigNumber);
writer.WritePropertyName("Street");
writer.WriteValue(c.BigNumber);
writer.WriteEndObject();
writer.WritePropertyName("Addresses");
writer.WriteStartArray();
foreach (Address address in c.Addresses)
{
writer.WriteStartObject();
writer.WritePropertyName("Street");
writer.WriteValue(address.Street);
writer.WritePropertyName("Phone");
writer.WriteValue(address.Phone);
writer.WritePropertyName("Entered");
writer.WriteValue(address.Entered);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
return sw.ToString();
}
#endregion
[Benchmark]
public Task<string> JsonNetManualAsync()
{
return SerializeJsonNetManualAsync(TestClass, Formatting.None);
}
[Benchmark]
public Task<string> JsonNetManualIndentedAsync()
{
return SerializeJsonNetManualAsync(TestClass, Formatting.Indented);
}
private async Task<string> SerializeJsonNetManualAsync(TestClass c, Formatting formatting)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = formatting;
await writer.WriteStartObjectAsync();
await writer.WritePropertyNameAsync("strings");
await writer.WriteStartArrayAsync();
foreach (string s in c.strings)
{
await writer.WriteValueAsync(s);
}
await writer.WriteEndArrayAsync();
await writer.WritePropertyNameAsync("dictionary");
await writer.WriteStartObjectAsync();
foreach (KeyValuePair<string, int> keyValuePair in c.dictionary)
{
await writer.WritePropertyNameAsync(keyValuePair.Key);
await writer.WriteValueAsync(keyValuePair.Value);
}
await writer.WriteEndObjectAsync();
await writer.WritePropertyNameAsync("Name");
await writer.WriteValueAsync(c.Name);
await writer.WritePropertyNameAsync("Now");
await writer.WriteValueAsync(c.Now);
await writer.WritePropertyNameAsync("BigNumber");
await writer.WriteValueAsync(c.BigNumber);
await writer.WritePropertyNameAsync("Address1");
await writer.WriteStartObjectAsync();
await writer.WritePropertyNameAsync("Street");
await writer.WriteValueAsync(c.BigNumber);
await writer.WritePropertyNameAsync("Street");
await writer.WriteValueAsync(c.BigNumber);
await writer.WritePropertyNameAsync("Street");
await writer.WriteValueAsync(c.BigNumber);
await writer.WriteEndObjectAsync();
await writer.WritePropertyNameAsync("Addresses");
await writer.WriteStartArrayAsync();
foreach (Address address in c.Addresses)
{
await writer.WriteStartObjectAsync();
await writer.WritePropertyNameAsync("Street");
await writer.WriteValueAsync(address.Street);
await writer.WritePropertyNameAsync("Phone");
await writer.WriteValueAsync(address.Phone);
await writer.WritePropertyNameAsync("Entered");
await writer.WriteValueAsync(address.Entered);
await writer.WriteEndObjectAsync();
}
await writer.WriteEndArrayAsync();
await writer.WriteEndObjectAsync();
await writer.FlushAsync();
return sw.ToString();
}
#pragma warning disable 618
[Benchmark]
public byte[] JsonNetBson()
{
return SerializeJsonNetBson(TestClass);
}
private static readonly byte[] Buffer = new byte[4096];
private byte[] SerializeJsonNetBson(TestClass c)
{
MemoryStream ms = new MemoryStream(Buffer);
JsonSerializer serializer = new JsonSerializer();
BsonWriter writer = new BsonWriter(ms);
serializer.Serialize(writer, c);
return ms.ToArray();
}
#pragma warning restore 618
}
}
@@ -0,0 +1,65 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using BenchmarkDotNet.Attributes;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Benchmarks
{
public class XmlNodeConverterBenchmarks
{
[Benchmark]
public void ConvertXmlNode()
{
XmlDocument doc = new XmlDocument();
using (FileStream file = System.IO.File.OpenRead("large_sample.xml"))
{
doc.Load(file);
}
JsonConvert.SerializeXmlNode(doc);
}
[Benchmark]
public void ConvertXNode()
{
XDocument doc;
using (FileStream file = System.IO.File.OpenRead("large_sample.xml"))
{
doc = XDocument.Load(file);
}
JsonConvert.SerializeXNode(doc);
}
}
}
@@ -18,6 +18,7 @@
<DebugType Condition="'$(TargetFramework)' != '' AND '$(TargetFramework)' != 'netcoreapp1.0'">Full</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Condition="'$(TargetFramework)' != '' AND '$(TargetFramework)' != 'net45'" Remove="Benchmarks\**" />
<None Include="large.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
@@ -42,6 +43,7 @@
<PackageReference Include="NUnit" Version="3.6.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.7.0" />
<PackageReference Include="Autofac" Version="4.0.0-rc2-240" />
<PackageReference Include="BenchmarkDotNet" Version="0.10.2" />
<PackageReference Include="FSharp.Core" Version="4.0.1.7-alpha" />
<PackageReference Include="System.Buffers" Version="4.0.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
@@ -49,6 +49,19 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Benchmarks\BenchmarkConstants.cs" />
<Compile Include="Benchmarks\SerializeBenchmarks.cs" />
<Compile Include="Benchmarks\XmlNodeConverterBenchmarks.cs" />
<Compile Include="Benchmarks\JsonTextWriterBenchmarks.cs" />
<Compile Include="Benchmarks\JsonTextReaderBenchmarks.cs" />
<Compile Include="Benchmarks\SerializeComparisonBenchmarks.cs" />
<Compile Include="Benchmarks\DeserializeComparisonBenchmarks.cs" />
<Compile Include="Benchmarks\DeserializeBenchmarks.cs" />
<Compile Include="Benchmarks\JValueConvertBenchmarks.cs" />
<Compile Include="Benchmarks\LargeJArrayBenchmarks.cs" />
<Compile Include="Benchmarks\JTokenBenchmarks.cs" />
<Compile Include="Benchmarks\LowLevelBenchmarks.cs" />
<Compile Include="Benchmarks\Runner.cs" />
<Compile Include="Bson\BsonReaderAsyncTests.cs" />
<Compile Include="Bson\BsonReaderTests.cs" />
<Compile Include="Bson\BsonWriterAsyncTests.cs" />
@@ -240,6 +253,8 @@
<Compile Include="Linq\JTokenWriterAsyncTests.cs" />
<Compile Include="Linq\JValueAsyncTests.cs" />
<Compile Include="Linq\LinqToJsonAsyncTests.cs" />
<Compile Include="TestObjects\Address.cs" />
<Compile Include="TestObjects\Friend.cs" />
<Compile Include="TestObjects\JsonReaderStubWithIsClosed.cs" />
<Compile Include="TestObjects\JsonTextReaderTests\FakeArrayPool.cs" />
<Compile Include="JsonTextReaderTests\FloatTests.cs" />
@@ -456,6 +471,7 @@
<Compile Include="TestObjects\RoleTransfer.cs" />
<Compile Include="TestObjects\RoleTransferDirection.cs" />
<Compile Include="TestObjects\RoleTransferOperation.cs" />
<Compile Include="TestObjects\RootObject.cs" />
<Compile Include="TestObjects\SearchResult.cs" />
<Compile Include="TestObjects\SelectListItem.cs" />
<Compile Include="TestObjects\SerializationEventTestDictionary.cs" />
@@ -477,6 +493,7 @@
<Compile Include="TestObjects\SubKlass.cs" />
<Compile Include="TestObjects\SuperKlass.cs" />
<Compile Include="TestObjects\GeometricForms\Tags.cs" />
<Compile Include="TestObjects\TestClass.cs" />
<Compile Include="TestObjects\TestComponent.cs" />
<Compile Include="TestObjects\TestComponentSimple.cs" />
<Compile Include="TestObjects\TestObject.cs" />
@@ -1,6 +1,7 @@
{
"dependencies": {
"Autofac": "4.0.0-rc2-240",
"BenchmarkDotNet": "0.10.2",
"FSharp.Core": "4.0.0.1",
"NUnit": "2.6.2",
"System.Buffers": "4.0.0",
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -234,7 +234,7 @@ namespace Newtonsoft.Json.Tests
return hex;
}
protected byte[] HexToBytes(string hex)
public static byte[] HexToBytes(string hex)
{
string fixedHex = hex.Replace("-", string.Empty);
@@ -0,0 +1,65 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
#if !(NET20 || DNXCORE50)
[Serializable]
[DataContract]
public class Address
{
[DataMember]
public string Street
{
get { return _street; }
set { _street = value; }
}
private string _street = "32 Kaiea";
[DataMember]
public string Phone
{
get { return _Phone; }
set { _Phone = value; }
}
private string _Phone = "(503) 814-6335";
[DataMember]
public DateTime Entered
{
get { return _Entered; }
set { _Entered = value; }
}
private DateTime _Entered = DateTime.Parse("01/01/2007", CultureInfo.CurrentCulture.DateTimeFormat);
}
#endif
}
@@ -0,0 +1,35 @@
using System.Linq;
using System.Text;
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Friend
{
public int id { get; set; }
public string name { get; set; }
}
}
@@ -0,0 +1,56 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class RootObject
{
public string _id { get; set; }
public int index { get; set; }
public Guid guid { get; set; }
public bool isActive { get; set; }
public string balance { get; set; }
public Uri picture { get; set; }
public int age { get; set; }
public string eyeColor { get; set; }
public string name { get; set; }
public string gender { get; set; }
public string company { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string address { get; set; }
public string about { get; set; }
public DateTime registered { get; set; }
public double latitude { get; set; }
public decimal longitude { get; set; }
public List<string> tags { get; set; }
public List<Friend> friends { get; set; }
public string greeting { get; set; }
public string favoriteFruit { get; set; }
}
}
@@ -0,0 +1,89 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
#if !(NET20 || DNXCORE50)
[Serializable]
[DataContract]
public class TestClass
{
[DataMember]
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private string _Name = "Rick";
[DataMember]
public DateTime Now
{
get { return _Now; }
set { _Now = value; }
}
private DateTime _Now = DateTime.Now;
[DataMember]
public decimal BigNumber
{
get { return _BigNumber; }
set { _BigNumber = value; }
}
private decimal _BigNumber = 1212121.22M;
[DataMember]
public Address Address1
{
get { return _Address1; }
set { _Address1 = value; }
}
private Address _Address1 = new Address();
[DataMember]
public List<Address> Addresses
{
get { return _Addresses; }
set { _Addresses = value; }
}
private List<Address> _Addresses = new List<Address>();
[DataMember]
public List<string> strings = new List<string>();
[DataMember]
public Dictionary<string, int> dictionary = new Dictionary<string, int>();
}
#endif
}
@@ -274,6 +274,7 @@
<ItemGroup>
<EmbeddedResource Include="Dynamic.snk" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -1361,9 +1361,9 @@ namespace Newtonsoft.Json.Utilities
{
value = 0M;
const decimal decimalMaxValueHi28 = 7922816251426433759354395033M;
const ulong decimalMaxValueHi19 = 7922816251426433759UL;
const ulong decimalMaxValueLo9 = 354395033UL;
const char decimalMaxValueLo1 = '5';
const ulong decimalMaxValueHi19 = 7922816251426433759UL;
const ulong decimalMaxValueLo9 = 354395033UL;
const char decimalMaxValueLo1 = '5';
if (length == 0)
{
@@ -1505,7 +1505,7 @@ namespace Newtonsoft.Json.Utilities
{
hi19 = (hi19 * 10UL) + (ulong)(c - '0');
}
else
else
{
lo10 = (lo10 * 10UL) + (ulong)(c - '0');
}
@@ -1673,4 +1673,4 @@ namespace Newtonsoft.Json.Utilities
return true;
}
}
}
}