Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions YamlDotNet.Benchmark/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
using System.Diagnostics;
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// 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.

using BenchmarkDotNet.Running;
using YamlDotNet.Benchmark;
using YamlDotNet.Serialization;

var serializer = new SerializerBuilder().JsonCompatible().Build();
var v = new { nan = float.NaN, inf = float.NegativeInfinity, posinf = float.PositiveInfinity, max = float.MaxValue, min = float.MinValue, good = .1234f, good1 = 1, good2 = -.1234, good3= -1 };
var yaml = serializer.Serialize(v);
Console.WriteLine(yaml);
BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
Original file line number Diff line number Diff line change
Expand Up @@ -19,36 +19,36 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Collections.Generic;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using YamlDotNet.Serialization;

namespace YamlDotNet.Serialization.Utilities
namespace YamlDotNet.Benchmark;

[MemoryDiagnoser]
[MediumRunJob(RuntimeMoniker.Net80)]
[MediumRunJob(RuntimeMoniker.Net47)]
public class SerializationBenchmarks
{
internal static class ReflectionUtility
public class SampleRecord
{
public static Type? GetImplementedGenericInterface(Type type, Type genericInterfaceType)
public SampleRecord(string name, string description)
{
foreach (var interfacetype in GetImplementedInterfaces(type))
{
if (interfacetype.IsGenericType() && interfacetype.GetGenericTypeDefinition() == genericInterfaceType)
{
return interfacetype;
}
}
return null;
Name = name;
Description = description;
}

public static IEnumerable<Type> GetImplementedInterfaces(Type type)
{
if (type.IsInterface())
{
yield return type;
}
public string Name { get; private set; }
public string Description { get; private set; }
}

foreach (var implementedInterface in type.GetInterfaces())
{
yield return implementedInterface;
}
}
private readonly IReadOnlyCollection<SampleRecord> configs = Enumerable.Range(0, 10_000).Select(i => new SampleRecord("MyName", "MyDescription")).ToList();
private readonly ISerializer serializer = new SerializerBuilder().DisableAliases().Build();

[Benchmark]
public string Serializer()
{
return serializer.Serialize(configs);
}
}
8 changes: 5 additions & 3 deletions YamlDotNet.Benchmark/YamlDotNet.Benchmark.csproj
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>net8.0;net47</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>10.0</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.1" />
<PackageReference Include="BenchmarkDotNet" Version="0.14.0" />
<PackageReference Include="System.Reflection.Metadata" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
23 changes: 23 additions & 0 deletions YamlDotNet/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,29 @@ public static bool IsGenericTypeDefinition(this Type type)
return type.GetTypeInfo().IsGenericTypeDefinition;
}

public static Type? GetImplementationOfOpenGenericInterface(this Type type, Type openGenericType)
{
if (!openGenericType.IsGenericType || !openGenericType.IsInterface)
{
// Note we can likely relax this constraint to also allow for matching other types
throw new ArgumentException("The type must be a generic type definition and an interface", nameof(openGenericType));
}

// First check if the type itself is the open generic type
if (IsGenericDefinitionOfType(type, openGenericType))
{
return type;
}

// Then check the interfaces
return type.FindInterfaces(static (t, context) => IsGenericDefinitionOfType(t, context), openGenericType).FirstOrDefault();

static bool IsGenericDefinitionOfType(Type t, object? context)
{
return t.IsGenericType && t.GetGenericTypeDefinition() == (Type)context;
}
}

public static bool IsInterface(this Type type)
{
return type.GetTypeInfo().IsInterface;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, o
IList? list;
var canUpdate = true;
Type itemType;
var genericCollectionType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>));
var genericCollectionType = expectedType.GetImplementationOfOpenGenericInterface((typeof(ICollection<>)));
if (genericCollectionType != null)
{
var genericArguments = genericCollectionType.GetGenericArguments();
Expand All @@ -58,7 +58,7 @@ public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, o
if (list == null)
{
// Uncommon case where a type implements IList<T> but not IList
var genericListType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IList<>));
var genericListType = expectedType.GetImplementationOfOpenGenericInterface(typeof(IList<>));
canUpdate = genericListType != null;
list = (IList?)Activator.CreateInstance(typeof(GenericCollectionToNonGenericAdapter<>).MakeGenericType(itemType), value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, o
{
IDictionary? dictionary;
Type keyType, valueType;
var genericDictionaryType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<,>));
var genericDictionaryType = expectedType.GetImplementationOfOpenGenericInterface(typeof(IDictionary<,>));
if (genericDictionaryType != null)
{
var genericArguments = genericDictionaryType.GetGenericArguments();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, o
}
else
{
var iEnumerable = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>));
var iEnumerable = expectedType.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>));
if (iEnumerable != expectedType)
{
value = null;
Expand Down
4 changes: 2 additions & 2 deletions YamlDotNet/Serialization/ObjectFactories/ObjectFactoryBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public virtual void ExecuteOnSerializing(object value)

public virtual bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments)
{
var genericDictionaryType = ReflectionUtility.GetImplementedGenericInterface(descriptor.Type, typeof(IDictionary<,>));
var genericDictionaryType = descriptor.Type.GetImplementationOfOpenGenericInterface(typeof(IDictionary<,>));
if (genericDictionaryType != null)
{
genericArguments = genericDictionaryType.GetGenericArguments();
Expand All @@ -70,7 +70,7 @@ public virtual bool GetDictionary(IObjectDescriptor descriptor, out IDictionary?

public virtual Type GetValueType(Type type)
{
var enumerableType = ReflectionUtility.GetImplementedGenericInterface(type, typeof(IEnumerable<>));
var enumerableType = type.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>));
var itemType = enumerableType != null ? enumerableType.GetGenericArguments()[0] : typeof(object);
return itemType;
}
Expand Down