Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pool string builders per-thread. #36

Merged
merged 1 commit into from
Mar 20, 2024
Merged
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
33 changes: 17 additions & 16 deletions src/TypeNameInterpretation/BuilderPool.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
// Copyright (c) Brian Reichle. All Rights Reserved. Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Text;
using System.Threading;

namespace TypeNameInterpretation
{
static class BuilderPool
{
public static StringBuilder Rent()
=> Interlocked.Exchange(ref _cache, null) ?? new StringBuilder();
{
var result = _cache ?? new StringBuilder();
_cache = null;
return result;
}

public static StringBuilder Rent(int capacity)
{
var result = Interlocked.Exchange(ref _cache, null);
var result = _cache;
_cache = null;

if (result == null)
{
return new StringBuilder(capacity);
}

result.EnsureCapacity(capacity);
return result;
else
{
result.EnsureCapacity(capacity);
return result;
}
}

public static void Return(StringBuilder builder)
Expand All @@ -29,19 +36,12 @@ public static void Return(StringBuilder builder)
return;
}

builder.Length = 0;
var existing = _cache;

while (existing == null || existing.Capacity < builder.Capacity)
if (existing == null || existing.Capacity < builder.Capacity)
{
var tmp = Interlocked.CompareExchange(ref _cache, builder, existing);

if (tmp == existing)
{
return;
}

existing = tmp;
builder.Length = 0;
_cache = builder;
}
}

Expand All @@ -52,6 +52,7 @@ public static string ToStringAndReturn(this StringBuilder builder)
return result;
}

[ThreadStatic]
static StringBuilder? _cache;
}
}
Loading