fix: Adds optimized formatter for clilocs (#1045)

Adds an optimized formatter for localization. Example:
```cs
string localizationText = Localization.Format(1050039, "enu", $"{m_Amount}\t{LabelNumber:#}");
```

Fixes #1044
This commit is contained in:
Kamron Batman 2022-06-04 11:53:32 -07:00 committed by GitHub
parent ecbee17690
commit 5f00330a66
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 248 additions and 53 deletions

View file

@ -22,11 +22,13 @@ public struct PooledArraySpanFormattable : ISpanFormattable, IDisposable
{
private char[] _arrayToReturnToPool;
private int _pos;
private string _value;
public PooledArraySpanFormattable(char[] arrayToReturnToPool, int length)
{
_arrayToReturnToPool = arrayToReturnToPool;
_pos = length;
_value = null;
}
public ReadOnlySpan<char> Chars => _arrayToReturnToPool.AsSpan(.._pos);
@ -35,10 +37,12 @@ public struct PooledArraySpanFormattable : ISpanFormattable, IDisposable
public string ToString(string? format = null, IFormatProvider formatProvider = null)
{
var result = new string(_arrayToReturnToPool.AsSpan(0, _pos));
Dispose();
_value ??= new string(_arrayToReturnToPool.AsSpan(0, _pos));
return result;
STArrayPool<char>.Shared.Return(_arrayToReturnToPool);
_arrayToReturnToPool = null;
return _value;
}
public bool TryFormat(
@ -53,18 +57,14 @@ public struct PooledArraySpanFormattable : ISpanFormattable, IDisposable
}
_arrayToReturnToPool.AsSpan(0, _pos).CopyTo(destination);
Dispose();
charsWritten = _pos;
return true;
}
public void Dispose()
{
if (_arrayToReturnToPool != null)
{
STArrayPool<char>.Shared.Return(_arrayToReturnToPool);
_arrayToReturnToPool = null;
}
STArrayPool<char>.Shared.Return(_arrayToReturnToPool);
_arrayToReturnToPool = null;
this = default; // Defensive clear
}
}

View file

@ -127,6 +127,11 @@ public class STArrayPool<T> : ArrayPool<T>
buckets[i]?.Trim(ticks, pressure, GetMaxSizeForBucket(i));
}
if (_cacheBuckets == null)
{
return true;
}
// Under high pressure, release all cached buckets
if (pressure == MemoryPressure.High)
{