fix: Updates ArrayPool to STArrayPool for performance. (#968)

This commit is contained in:
Kamron Batman 2022-03-22 20:07:32 -07:00 • committed by GitHub
parent 76fddcbccd
commit 14b63ca48e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 3163 additions and 3165 deletions

View file

@ -11,7 +11,7 @@ namespace Server.Tests.Network
{ {
private async void DelayedExecute(Action action) private async void DelayedExecute(Action action)
{ {
await Task.Delay(5); await Task.Delay(1);
action(); action();
} }
@ -130,8 +130,12 @@ namespace Server.Tests.Network
continue; continue;
} }
result.CopyFrom(new[] { expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, result.CopyFrom(new[] {
expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value, expected_value }); expected_value, expected_value, expected_value, expected_value,
expected_value, expected_value, expected_value, expected_value,
expected_value, expected_value, expected_value, expected_value,
expected_value, expected_value, expected_value, expected_value
});
writer.Advance(16); writer.Advance(16);
count += 16; count += 16;

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright 2019-2020 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: SpanWriter.cs * * File: SpanWriter.cs *
* * * *
@ -22,12 +22,13 @@ using System.Runtime.InteropServices;
using System.Text; using System.Text;
using Microsoft.Toolkit.HighPerformance; using Microsoft.Toolkit.HighPerformance;
using Server; using Server;
using Server.Buffers;
using Server.Text; using Server.Text;
namespace System.Buffers namespace System.Buffers;
public ref struct SpanWriter
{ {
public ref struct SpanWriter
{
private readonly bool _resize; private readonly bool _resize;
private byte[] _arrayToReturnToPool; private byte[] _arrayToReturnToPool;
private Span<byte> _buffer; private Span<byte> _buffer;
@ -75,7 +76,7 @@ namespace System.Buffers
apo = new SpanOwner(_position, Array.Empty<byte>()); apo = new SpanOwner(_position, Array.Empty<byte>());
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
else if (toReturn != null) else if (toReturn != null)
@ -84,7 +85,7 @@ namespace System.Buffers
} }
else else
{ {
var buffer = ArrayPool<byte>.Shared.Rent(_position); var buffer = STArrayPool<byte>.Shared.Rent(_position);
_buffer.CopyTo(buffer); _buffer.CopyTo(buffer);
apo = new SpanOwner(_position, buffer); apo = new SpanOwner(_position, buffer);
} }
@ -107,7 +108,7 @@ namespace System.Buffers
public SpanWriter(int initialCapacity, bool resize = false) public SpanWriter(int initialCapacity, bool resize = false)
{ {
_resize = resize; _resize = resize;
_arrayToReturnToPool = ArrayPool<byte>.Shared.Rent(initialCapacity); _arrayToReturnToPool = STArrayPool<byte>.Shared.Rent(initialCapacity);
_buffer = _arrayToReturnToPool; _buffer = _arrayToReturnToPool;
_position = 0; _position = 0;
BytesWritten = 0; BytesWritten = 0;
@ -117,7 +118,7 @@ namespace System.Buffers
private void Grow(int additionalCapacity) private void Grow(int additionalCapacity)
{ {
var newSize = Math.Max(BytesWritten + additionalCapacity, _buffer.Length * 2); var newSize = Math.Max(BytesWritten + additionalCapacity, _buffer.Length * 2);
byte[] poolArray = ArrayPool<byte>.Shared.Rent(newSize); byte[] poolArray = STArrayPool<byte>.Shared.Rent(newSize);
_buffer[..BytesWritten].CopyTo(poolArray); _buffer[..BytesWritten].CopyTo(poolArray);
@ -125,7 +126,7 @@ namespace System.Buffers
_buffer = _arrayToReturnToPool = poolArray; _buffer = _arrayToReturnToPool = poolArray;
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
@ -422,7 +423,7 @@ namespace System.Buffers
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
@ -451,8 +452,7 @@ namespace System.Buffers
this = default; this = default;
if (_length > 0) if (_length > 0)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
}
} }
} }
} }

View file

@ -2,15 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license. // The .NET Foundation licenses this file to you under the MIT license.
using System; using System;
using System.Buffers;
using System.Globalization; using System.Globalization;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Server.Buffers namespace Server.Buffers;
public ref struct ValueStringBuilder
{ {
public ref struct ValueStringBuilder
{
private char[] _arrayToReturnToPool; private char[] _arrayToReturnToPool;
private Span<char> _chars; private Span<char> _chars;
private int _length; private int _length;
@ -36,7 +35,7 @@ namespace Server.Buffers
// If this ctor is used, you cannot pass in stackalloc ROS for append/replace. // If this ctor is used, you cannot pass in stackalloc ROS for append/replace.
public ValueStringBuilder(int initialCapacity) public ValueStringBuilder(int initialCapacity)
{ {
_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _arrayToReturnToPool = STArrayPool<char>.Shared.Rent(initialCapacity);
_chars = _arrayToReturnToPool; _chars = _arrayToReturnToPool;
_length = 0; _length = 0;
} }
@ -352,7 +351,7 @@ namespace Server.Buffers
[MethodImpl(MethodImplOptions.NoInlining)] [MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacityBeyondPos) private void Grow(int additionalCapacityBeyondPos)
{ {
char[] poolArray = ArrayPool<char>.Shared.Rent(Math.Max(_length + additionalCapacityBeyondPos, _chars.Length * 2)); char[] poolArray = STArrayPool<char>.Shared.Rent(Math.Max(_length + additionalCapacityBeyondPos, _chars.Length * 2));
_chars[.._length].CopyTo(poolArray); _chars[.._length].CopyTo(poolArray);
@ -360,7 +359,7 @@ namespace Server.Buffers
_chars = _arrayToReturnToPool = poolArray; _chars = _arrayToReturnToPool = poolArray;
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<char>.Shared.Return(toReturn); STArrayPool<char>.Shared.Return(toReturn);
} }
} }
@ -371,7 +370,7 @@ namespace Server.Buffers
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<char>.Shared.Return(toReturn); STArrayPool<char>.Shared.Return(toReturn);
} }
} }
#nullable restore #nullable restore
@ -470,5 +469,4 @@ namespace Server.Buffers
_length -= length; _length -= length;
} }
}
} }

View file

@ -14,18 +14,18 @@
*************************************************************************/ *************************************************************************/
using System; using System;
using System.Buffers;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Microsoft.Collections.Extensions; using Microsoft.Collections.Extensions;
using Server.Buffers;
namespace Server.Collections namespace Server.Collections;
[DebuggerDisplay("Count = {Count}")]
public class PooledOrderedHashSet<TValue> : IList<TValue>, IDisposable
{ {
[DebuggerDisplay("Count = {Count}")]
public class PooledOrderedHashSet<TValue> : IList<TValue>, IDisposable
{
private struct Entry private struct Entry
{ {
public uint HashCode; public uint HashCode;
@ -70,9 +70,9 @@ namespace Server.Collections
if (capacity > 0) if (capacity > 0)
{ {
int newSize = HashHelpers.GetPrime(capacity); int newSize = HashHelpers.GetPrime(capacity);
_buckets = ArrayPool<int>.Shared.Rent(newSize); _buckets = STArrayPool<int>.Shared.Rent(newSize);
_bucketsLength = newSize; _bucketsLength = newSize;
_entries = ArrayPool<Entry>.Shared.Rent(newSize); _entries = STArrayPool<Entry>.Shared.Rent(newSize);
_entriesLength = newSize; _entriesLength = newSize;
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize); _fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize);
} }
@ -262,8 +262,8 @@ namespace Server.Collections
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private Entry[] Resize(int newSize) private Entry[] Resize(int newSize)
{ {
int[] newBuckets = _buckets.Length < newSize ? ArrayPool<int>.Shared.Rent(newSize) : _buckets; int[] newBuckets = _buckets.Length < newSize ? STArrayPool<int>.Shared.Rent(newSize) : _buckets;
Entry[] newEntries = _entries.Length < newSize ? ArrayPool<Entry>.Shared.Rent(newSize) : _entries; Entry[] newEntries = _entries.Length < newSize ? STArrayPool<Entry>.Shared.Rent(newSize) : _entries;
int count = Count; int count = Count;
Array.Copy(_entries, newEntries, count); Array.Copy(_entries, newEntries, count);
@ -280,12 +280,12 @@ namespace Server.Collections
if (oldBuckets.Length > 1 && oldBuckets != newBuckets) if (oldBuckets.Length > 1 && oldBuckets != newBuckets)
{ {
ArrayPool<int>.Shared.Return(oldBuckets, true); STArrayPool<int>.Shared.Return(oldBuckets, true);
} }
if (oldEntries.Length > 1 && oldEntries != newEntries) if (oldEntries.Length > 1 && oldEntries != newEntries)
{ {
ArrayPool<Entry>.Shared.Return(oldEntries, true); STArrayPool<Entry>.Shared.Return(oldEntries, true);
} }
_buckets = newBuckets; _buckets = newBuckets;
@ -568,12 +568,12 @@ namespace Server.Collections
{ {
if (_buckets.Length > 1) if (_buckets.Length > 1)
{ {
ArrayPool<int>.Shared.Return(_buckets, true); STArrayPool<int>.Shared.Return(_buckets, true);
} }
if (_entries.Length > 1) if (_entries.Length > 1)
{ {
ArrayPool<Entry>.Shared.Return(_entries, true); STArrayPool<Entry>.Shared.Return(_entries, true);
} }
_buckets = HashHelpers.SizeOneIntArray; _buckets = HashHelpers.SizeOneIntArray;
@ -587,17 +587,16 @@ namespace Server.Collections
{ {
if (_buckets.Length > 1) if (_buckets.Length > 1)
{ {
ArrayPool<int>.Shared.Return(_buckets, true); STArrayPool<int>.Shared.Return(_buckets, true);
} }
if (_entries.Length > 1) if (_entries.Length > 1)
{ {
ArrayPool<Entry>.Shared.Return(_entries, true); STArrayPool<Entry>.Shared.Return(_entries, true);
} }
_buckets = HashHelpers.SizeOneIntArray; _buckets = HashHelpers.SizeOneIntArray;
_entries = InitialEntries; _entries = InitialEntries;
_count = 0; _count = 0;
} }
}
} }

View file

@ -1,20 +1,20 @@
using System; using System;
using System.Buffers;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Server.Buffers;
using Server.Items; using Server.Items;
using Server.Logging; using Server.Logging;
using Server.Network; using Server.Network;
using Server.Targeting; using Server.Targeting;
namespace Server namespace Server;
[Flags]
public enum MapRules
{ {
[Flags]
public enum MapRules
{
None = 0x0000, None = 0x0000,
Internal = 0x0001, // Internal map (used for dragging, commodity deeds, etc) Internal = 0x0001, // Internal map (used for dragging, commodity deeds, etc)
FreeMovement = 0x0002, // Anyone can move over anyone else without taking stamina loss FreeMovement = 0x0002, // Anyone can move over anyone else without taking stamina loss
@ -22,19 +22,19 @@ namespace Server
HarmfulRestrictions = 0x0008, // Disallow performing harmful actions on innocents HarmfulRestrictions = 0x0008, // Disallow performing harmful actions on innocents
TrammelRules = FreeMovement | BeneficialRestrictions | HarmfulRestrictions, TrammelRules = FreeMovement | BeneficialRestrictions | HarmfulRestrictions,
FeluccaRules = None FeluccaRules = None
} }
public interface IPooledEnumerable : IEnumerable public interface IPooledEnumerable : IEnumerable
{ {
void Free(); void Free();
} }
public interface IPooledEnumerable<T> : IPooledEnumerable, IEnumerable<T> public interface IPooledEnumerable<T> : IPooledEnumerable, IEnumerable<T>
{ {
} }
public static class PooledEnumeration public static class PooledEnumeration
{ {
public delegate IEnumerable<T> Selector<out T>(Sector sector, Rectangle2D bounds); public delegate IEnumerable<T> Selector<out T>(Sector sector, Rectangle2D bounds);
static PooledEnumeration() static PooledEnumeration()
@ -311,11 +311,11 @@ namespace Server
s = map.GetRealSector(xSector, ySector); s = map.GetRealSector(xSector, ySector);
return true; return true;
} }
} }
[Parsable] [Parsable]
public sealed class Map : IComparable<Map> public sealed class Map : IComparable<Map>
{ {
public const int SectorSize = 16; public const int SectorSize = 16;
public const int SectorShift = 4; public const int SectorShift = 4;
public const int SectorActiveRange = 2; public const int SectorActiveRange = 2;
@ -623,7 +623,7 @@ namespace Server
GetAverageZ(x, y, out _, out var landAvg, out _); GetAverageZ(x, y, out _, out var landAvg, out _);
var items = ArrayPool<Item>.Shared.Rent(128); var items = STArrayPool<Item>.Shared.Rent(128);
AcquireFixItems(this, x, y, items, out var length); AcquireFixItems(this, x, y, items, out var length);
for (var i = 0; i < length; i++) for (var i = 0; i < length; i++)
@ -691,7 +691,7 @@ namespace Server
} }
} }
ArrayPool<Item>.Shared.Return(items, true); STArrayPool<Item>.Shared.Return(items, true);
} }
/* This could probably be re-implemented if necessary (perhaps via an ITile interface?). /* This could probably be re-implemented if necessary (perhaps via an ITile interface?).
@ -1685,5 +1685,4 @@ namespace Server
} }
} }
#pragma warning restore CA1000 // Do not declare static members on generic types #pragma warning restore CA1000 // Do not declare static members on generic types
}
} }

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: OutgoingGumpPackets.cs * * File: OutgoingGumpPackets.cs *
* * * *
@ -18,6 +18,7 @@ using System.Buffers;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Server.Buffers;
using Server.Collections; using Server.Collections;
using Server.Gumps; using Server.Gumps;
using Server.Logging; using Server.Logging;
@ -68,7 +69,7 @@ public static class OutgoingGumpPackets
if (wantLength > packBuffer.Length) if (wantLength > packBuffer.Length)
{ {
packBuffer = rentedBuffer = ArrayPool<byte>.Shared.Rent(wantLength); packBuffer = rentedBuffer = STArrayPool<byte>.Shared.Rent(wantLength);
} }
var packLength = wantLength; var packLength = wantLength;
@ -90,7 +91,7 @@ public static class OutgoingGumpPackets
if (rentedBuffer != null) if (rentedBuffer != null)
{ {
ArrayPool<byte>.Shared.Return(rentedBuffer); STArrayPool<byte>.Shared.Return(rentedBuffer);
} }
} }

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright (C) 2019-2021 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: PacketContainerBuilder.cs * * File: PacketContainerBuilder.cs *
* * * *
@ -14,9 +14,9 @@
*************************************************************************/ *************************************************************************/
using System; using System;
using System.Buffers;
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Server.Buffers;
namespace Server.Network; namespace Server.Network;
@ -89,7 +89,7 @@ public ref struct PacketContainerBuilder
private void Grow(int additionalCapacityBeyondPos) private void Grow(int additionalCapacityBeyondPos)
{ {
var newLength = Math.Max(Length + additionalCapacityBeyondPos, _bytes.Length * 2); var newLength = Math.Max(Length + additionalCapacityBeyondPos, _bytes.Length * 2);
byte[] poolArray = ArrayPool<byte>.Shared.Rent(newLength); byte[] poolArray = STArrayPool<byte>.Shared.Rent(newLength);
_bytes[..Length].CopyTo(poolArray); _bytes[..Length].CopyTo(poolArray);
@ -97,7 +97,7 @@ public ref struct PacketContainerBuilder
_bytes = _arrayToReturnToPool = poolArray; _bytes = _arrayToReturnToPool = poolArray;
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
@ -108,7 +108,7 @@ public ref struct PacketContainerBuilder
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null) if (toReturn != null)
{ {
ArrayPool<byte>.Shared.Return(toReturn); STArrayPool<byte>.Shared.Return(toReturn);
} }
} }
} }

View file

@ -1,6 +1,6 @@
/************************************************************************* /*************************************************************************
* ModernUO * * ModernUO *
* Copyright (C) 2019-2020 - ModernUO Development Team * * Copyright 2019-2022 - ModernUO Development Team *
* Email: hi@modernuo.com * * Email: hi@modernuo.com *
* File: StringHelpers.cs * * File: StringHelpers.cs *
* * * *
@ -14,15 +14,15 @@
*************************************************************************/ *************************************************************************/
using System; using System;
using System.Buffers;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Server.Buffers;
namespace Server namespace Server;
public static class StringHelpers
{ {
public static class StringHelpers
{
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string DefaultIfNullOrEmpty(this string value, string def) => public static string DefaultIfNullOrEmpty(this string value, string def) =>
string.IsNullOrWhiteSpace(value) ? def : value; string.IsNullOrWhiteSpace(value) ? def : value;
@ -86,7 +86,7 @@ namespace Server
char[] chrs; char[] chrs;
if (span == null) if (span == null)
{ {
chrs = ArrayPool<char>.Shared.Rent(a.Length); chrs = STArrayPool<char>.Shared.Rent(a.Length);
span = chrs.AsSpan(); span = chrs.AsSpan();
} }
else else
@ -100,7 +100,7 @@ namespace Server
if (chrs != null) if (chrs != null)
{ {
ArrayPool<char>.Shared.Return(chrs); STArrayPool<char>.Shared.Return(chrs);
} }
return str; return str;
@ -118,7 +118,7 @@ namespace Server
char[] chrs; char[] chrs;
if (span == null) if (span == null)
{ {
chrs = ArrayPool<char>.Shared.Rent(value.Length); chrs = STArrayPool<char>.Shared.Rent(value.Length);
span = chrs.AsSpan(); span = chrs.AsSpan();
} }
else else
@ -163,7 +163,7 @@ namespace Server
if (chrs != null) if (chrs != null)
{ {
ArrayPool<char>.Shared.Return(chrs); STArrayPool<char>.Shared.Return(chrs);
} }
return str; return str;
@ -285,5 +285,4 @@ namespace Server
4 => MemoryMarshal.Cast<byte, uint>(buffer).IndexOf((uint)0) * 4, 4 => MemoryMarshal.Cast<byte, uint>(buffer).IndexOf((uint)0) * 4,
_ => buffer.IndexOf((byte)0) _ => buffer.IndexOf((byte)0)
}; };
}
} }

View file

@ -1,11 +1,11 @@
using System; using System;
using System.Buffers; using Server.Buffers;
using Server.Collections; using Server.Collections;
namespace Server.Mobiles namespace Server.Mobiles;
public class BladeSpirits : BaseCreature
{ {
public class BladeSpirits : BaseCreature
{
[Constructible] [Constructible]
public BladeSpirits() : base(AIType.AI_Melee) public BladeSpirits() : base(AIType.AI_Melee)
{ {
@ -94,7 +94,7 @@ namespace Server.Mobiles
Dispel(mobs[amount--]); Dispel(mobs[amount--]);
} }
ArrayPool<Mobile>.Shared.Return(mobs, true); STArrayPool<Mobile>.Shared.Return(mobs, true);
} }
} }
@ -114,5 +114,4 @@ namespace Server.Mobiles
var version = reader.ReadInt(); var version = reader.ReadInt();
} }
}
} }

View file

@ -1,15 +1,15 @@
using System; using System;
using System.Buffers; using Server.Buffers;
using Server.Collections; using Server.Collections;
namespace Server.Mobiles namespace Server.Mobiles;
public class EnergyVortex : BaseCreature
{ {
public class EnergyVortex : BaseCreature
{
[Constructible] [Constructible]
public EnergyVortex() : base(AIType.AI_Melee) public EnergyVortex() : base(AIType.AI_Melee)
{ {
if (Core.SE && Utility.RandomDouble() < 0.002) // Per OSI FoF, it's a 1/500 chance. if (Core.SE && Utility.Random(500) == 0) // Per OSI FoF, it's a 1/500 chance.
{ {
// Llama vortex! // Llama vortex!
Body = 0xDC; Body = 0xDC;
@ -100,7 +100,7 @@ namespace Server.Mobiles
Dispel(mobs[amount--]); Dispel(mobs[amount--]);
} }
ArrayPool<Mobile>.Shared.Return(mobs, true); STArrayPool<Mobile>.Shared.Return(mobs, true);
} }
} }
@ -125,5 +125,4 @@ namespace Server.Mobiles
BaseSoundID = 0; BaseSoundID = 0;
} }
} }
}
} }