Skip to content

Commit

Permalink
Merge pull request #108 from hadashiA/ku/perf-scalar-pool
Browse files Browse the repository at this point in the history
Optimize ScalarPool
  • Loading branch information
hadashiA authored Jun 1, 2024
2 parents bc05817 + a7edd07 commit 887eb8e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
24 changes: 18 additions & 6 deletions VYaml.Unity/Assets/VYaml/Runtime/Internal/Scalar.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#nullable enable
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading;
using VYaml.Internal;

namespace VYaml.Parser
Expand All @@ -12,21 +12,33 @@ class ScalarPool
{
public static readonly ScalarPool Shared = new();

readonly ConcurrentQueue<Scalar> queue = new();
readonly ConcurrentQueue<Scalar> items = new();
Scalar? fastItem;

public Scalar Rent()
{
if (queue.TryDequeue(out var value))
var value = fastItem;
if (value != null &&
Interlocked.CompareExchange(ref fastItem, null, value) == value)
{
return value;
}
if (items.TryDequeue(out value))
{
return value;
}
return new Scalar(256);
}

public void Return(Scalar scalar)
public void Return(Scalar value)
{
scalar.Clear();
queue.Enqueue(scalar);
value.Clear();

if (fastItem != null ||
Interlocked.CompareExchange(ref fastItem, value, null) != null)
{
items.Enqueue(value);
}
}
}

Expand Down
24 changes: 18 additions & 6 deletions VYaml/Internal/Scalar.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#nullable enable
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading;
using VYaml.Internal;

namespace VYaml.Parser
Expand All @@ -12,21 +12,33 @@ class ScalarPool
{
public static readonly ScalarPool Shared = new();

readonly ConcurrentQueue<Scalar> queue = new();
readonly ConcurrentQueue<Scalar> items = new();
Scalar? fastItem;

public Scalar Rent()
{
if (queue.TryDequeue(out var value))
var value = fastItem;
if (value != null &&
Interlocked.CompareExchange(ref fastItem, null, value) == value)
{
return value;
}
if (items.TryDequeue(out value))
{
return value;
}
return new Scalar(256);
}

public void Return(Scalar scalar)
public void Return(Scalar value)
{
scalar.Clear();
queue.Enqueue(scalar);
value.Clear();

if (fastItem != null ||
Interlocked.CompareExchange(ref fastItem, value, null) != null)
{
items.Enqueue(value);
}
}
}

Expand Down

0 comments on commit 887eb8e

Please sign in to comment.