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);
54 changes: 54 additions & 0 deletions YamlDotNet.Benchmark/SerializationBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// 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 System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using YamlDotNet.Serialization;

namespace YamlDotNet.Benchmark;

[MemoryDiagnoser]
[MediumRunJob(RuntimeMoniker.Net80)]
[MediumRunJob(RuntimeMoniker.Net47)]
public class SerializationBenchmarks
{
public class SampleRecord
{
public SampleRecord(string name, string description)
{
Name = name;
Description = description;
}

public string Name { get; private set; }
public string Description { get; private set; }
}

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
2 changes: 1 addition & 1 deletion YamlDotNet/Core/CharacterAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
namespace YamlDotNet.Core
{
[DebuggerStepThrough]
internal sealed class CharacterAnalyzer<TBuffer> where TBuffer : class, ILookAheadBuffer
internal readonly struct CharacterAnalyzer<TBuffer> where TBuffer : ILookAheadBuffer
{
public CharacterAnalyzer(TBuffer buffer)
{
Expand Down
8 changes: 5 additions & 3 deletions YamlDotNet/Core/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
using System.Text;
using System.Text.RegularExpressions;
using YamlDotNet.Core.Events;
using YamlDotNet.Helpers;
using YamlDotNet.Core.ObjectPool;
using ParsingEvent = YamlDotNet.Core.Events.ParsingEvent;
using TagDirective = YamlDotNet.Core.Tokens.TagDirective;
using VersionDirective = YamlDotNet.Core.Tokens.VersionDirective;
Expand Down Expand Up @@ -312,7 +312,8 @@ private void AnalyzeScalar(Scalar scalar)
blockIndicators = true;
}

var buffer = new CharacterAnalyzer<StringLookAheadBuffer>(new StringLookAheadBuffer(value));
using var slab = StringLookAheadBufferPool.Rent(value);
var buffer = new CharacterAnalyzer<StringLookAheadBuffer>(slab.Buffer);
var preceededByWhitespace = true;
var followedByWhitespace = buffer.IsWhiteBreakOrZero(1);

Expand Down Expand Up @@ -1793,7 +1794,8 @@ private bool CheckEmptyStructure<TStart, TEnd>()

private void WriteBlockScalarHints(string value)
{
var analyzer = new CharacterAnalyzer<StringLookAheadBuffer>(new StringLookAheadBuffer(value));
using var slab = StringLookAheadBufferPool.Rent(value);
var analyzer = new CharacterAnalyzer<StringLookAheadBuffer>(slab.Buffer);

if (analyzer.IsSpace() || analyzer.IsBreak())
{
Expand Down
123 changes: 123 additions & 0 deletions YamlDotNet/Core/ObjectPool/DefaultObjectPool.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// 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.


// Adapted from https://github.com/dotnet/aspnetcore/blob/2f1db20456007c9515068a35a65afdf99af70bc6/src/ObjectPool/src/DefaultObjectPool.cs which is
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Threading;

namespace YamlDotNet.Core.ObjectPool
{
/// <summary>
/// Default implementation of <see cref="ObjectPool{T}"/>.
/// </summary>
/// <typeparam name="T">The type to pool objects for.</typeparam>
/// <remarks>This implementation keeps a cache of retained objects. This means that if objects are returned when the pool has already reached "maximumRetained" objects they will be available to be Garbage Collected.</remarks>
internal class DefaultObjectPool<T> : ObjectPool<T> where T : class
{
private readonly Func<T> createFunc;
private readonly Func<T, bool> returnFunc;
private readonly int maxCapacity;
private int numItems;

private protected readonly ConcurrentQueue<T> items = new ConcurrentQueue<T>();
private protected T? fastItem;

/// <summary>
/// Creates an instance of <see cref="DefaultObjectPool{T}"/>.
/// </summary>
/// <param name="policy">The pooling policy to use.</param>
public DefaultObjectPool(IPooledObjectPolicy<T> policy)
: this(policy, Environment.ProcessorCount * 2)
{
}

/// <summary>
/// Creates an instance of <see cref="DefaultObjectPool{T}"/>.
/// </summary>
/// <param name="policy">The pooling policy to use.</param>
/// <param name="maximumRetained">The maximum number of objects to retain in the pool.</param>
public DefaultObjectPool(IPooledObjectPolicy<T> policy, int maximumRetained)
{
// cache the target interface methods, to avoid interface lookup overhead
createFunc = policy.Create;
returnFunc = policy.Return;
maxCapacity = maximumRetained - 1; // -1 to account for fastItem
}

/// <inheritdoc />
public override T Get()
{
var item = fastItem;
if (item == null || Interlocked.CompareExchange(ref fastItem, null, item) != item)
{
if (items.TryDequeue(out item))
{
Interlocked.Decrement(ref numItems);
return item;
}

// no object available, so go get a brand new one
return createFunc();
}

return item;
}

/// <inheritdoc />
public override void Return(T obj)
{
ReturnCore(obj);
}

/// <summary>
/// Returns an object to the pool.
/// </summary>
/// <returns>true if the object was returned to the pool</returns>
private protected bool ReturnCore(T obj)
{
if (!returnFunc(obj))
{
// policy says to drop this object
return false;
}

if (fastItem != null || Interlocked.CompareExchange(ref fastItem, obj, null) != null)
{
if (Interlocked.Increment(ref numItems) <= maxCapacity)
{
items.Enqueue(obj);
return true;
}

// no room, clean up the count and drop the object on the floor
Interlocked.Decrement(ref numItems);
return false;
}

return true;
}
}
}
52 changes: 52 additions & 0 deletions YamlDotNet/Core/ObjectPool/DefaultPooledObjectPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// 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.


// Adapted from https://github.com/dotnet/aspnetcore/blob/2f1db20456007c9515068a35a65afdf99af70bc6/src/ObjectPool/src/DefaultObjectPool.cs which is
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace YamlDotNet.Core.ObjectPool
{
/// <summary>
/// Default implementation for <see cref="PooledObjectPolicy{T}"/>.
/// </summary>
/// <typeparam name="T">The type of object which is being pooled.</typeparam>
internal class DefaultPooledObjectPolicy<T> : IPooledObjectPolicy<T> where T : class, new()
{
/// <inheritdoc />
public T Create()
{
return new T();
}

/// <inheritdoc />
public bool Return(T obj)
{
if (obj is IResettable resettable)
{
return resettable.TryReset();
}

return true;
}
}
}
48 changes: 48 additions & 0 deletions YamlDotNet/Core/ObjectPool/IPooledObjectPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// 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.


// Adapted from https://github.com/dotnet/aspnetcore/blob/2f1db20456007c9515068a35a65afdf99af70bc6/src/ObjectPool/src/DefaultObjectPool.cs which is
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace YamlDotNet.Core.ObjectPool
{
/// <summary>
/// Represents a policy for managing pooled objects.
/// </summary>
/// <typeparam name="T">The type of object which is being pooled.</typeparam>
internal interface IPooledObjectPolicy<T> where T : notnull
{
/// <summary>
/// Create a <typeparamref name="T"/>.
/// </summary>
/// <returns>The <typeparamref name="T"/> which was created.</returns>
T Create();

/// <summary>
/// Runs some processing when an object was returned to the pool. Can be used to reset the state of an object and indicate if the object should be returned to the pool.
/// </summary>
/// <param name="obj">The object to return to the pool.</param>
/// <returns><see langword="true" /> if the object should be returned to the pool. <see langword="false" /> if it's not possible/desirable for the pool to keep the object.</returns>
bool Return(T obj);
}
}
Loading