ModernUO/Projects/Server/Gumps/GumpStringsBuilder.cs
Kamron Batman 65532ea887
feat: Adds optimized dynamic/static layout gumps (#1652)
# New Gump API
We are pleased to release a new API that is faster, allocates nearly zero memory, and still feels very similar to the original API. The API is broken into 3 types of gumps, dynamic, static with placeholders, and static without placeholders. 

### Dynamic Gumps
These gumps will inherit `DynamicGump` and are meant for gumps that have a dynamic layout. This includes specifying dynamic arguments to HtmlLocalized entries.

## Static Gumps 
Static gumps are those where the function to the build the layout is called only once and cached forever. They can optionally have placeholders. These placeholders allow the developer to specify the string values later, dynamically in a `BuildStrings` method on the gump. If a gump does not have any placeholders, the string entries will also be cached forever.

## Benchmarks
To make sure we were going in the right direction and not wasting time, we took copious benchmarks. Here are the final benchmarks for a really simple gump. 

Note:
* The majority of creating a gump is compressing the layout and the strings. Compressing each section takes ~6,000ns (12us total).

```cs
| Method                         | Mean         | Error        | StdDev       | Median       | Ratio | RatioSD | Gen0   | Allocated | Alloc Ratio |
|------------------------------- |-------------:|-------------:|-------------:|-------------:|------:|--------:|-------:|----------:|------------:|
| OldGump                        | 13,308.29 ns | 1,059.695 ns | 1,883.608 ns | 14,330.72 ns | 1.000 |    0.00 | 0.1526 |    2400 B |        1.00 |
| DynamicLayoutGump              | 13,357.86 ns |   129.144 ns |   226.185 ns | 13,323.60 ns | 1.029 |    0.17 |      - |      48 B |        0.02 |
| StaticLayoutDynamicStringsGump |  6,653.10 ns |    81.815 ns |   143.292 ns |  6,617.45 ns | 0.514 |    0.09 |      - |      40 B |        0.02 |
| StaticLayoutGump               |     86.33 ns |     0.760 ns |     1.350 ns |     86.07 ns | 0.007 |    0.00 | 0.0020 |      32 B |        0.01 |
```

# Non-Breaking Changes
* All gump components in the core have been moved to `Gumps/Legacy`.
* All legacy gumps will still inherit `Gump`, which now inherits `BaseGump`

# Special Thanks

Thank you to @stefanomerotta for considerable contributions/benchmarking/testing to make this effort a reality! We collectively went through over 10 iterations, but it is finally ready.
2024-04-25 22:40:30 -07:00

127 lines
4.2 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2024 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GumpStringsBuilder.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Server.Buffers;
using Server.Text;
namespace Server.Gumps;
public ref struct GumpStringsBuilder
{
private static readonly byte[] _staticStringsBuffer = GC.AllocateUninitializedArray<byte>(0x80000);
private static readonly Dictionary<ulong, int> _hashes = new();
private readonly bool _finalizeLayout;
private byte[] _stringsBuffer;
private int _stringBytesWritten;
internal int _stringsCount;
internal ReadOnlySpan<byte> StringsBuffer => _stringsBuffer.AsSpan(0, _stringBytesWritten);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public GumpStringsBuilder(bool finalizeLayout)
{
_finalizeLayout = finalizeLayout;
_stringsBuffer = _staticStringsBuffer;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void GrowStringsBufferIfNeeded(int needed)
{
var newLength = needed + _stringBytesWritten;
if (newLength <= _stringsBuffer.Length)
{
return;
}
var newSize = Math.Max(newLength, _stringsBuffer.Length * 2);
byte[] poolArray = STArrayPool<byte>.Shared.Rent(newSize);
_stringsBuffer.AsSpan(0, _stringBytesWritten).CopyTo(poolArray);
byte[] toReturn = _stringsBuffer;
_stringsBuffer = poolArray;
if (toReturn != _staticStringsBuffer)
{
STArrayPool<byte>.Shared.Return(toReturn);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetStringSlot(ReadOnlySpan<char> slotKey, ref RawInterpolatedStringHandler handler)
{
SetStringSlot(slotKey, handler.Text);
handler.Clear();
}
public void SetStringSlot(ReadOnlySpan<char> slotKey, ReadOnlySpan<char> text)
{
var hash = HashUtility.ComputeHash64(slotKey);
if (text.Length > ushort.MaxValue)
{
text = text[..ushort.MaxValue];
}
GrowStringsBufferIfNeeded(2 + text.Length * 2);
BinaryPrimitives.WriteUInt16BigEndian(_stringsBuffer.AsSpan(_stringBytesWritten), (ushort)text.Length);
_stringBytesWritten += 2;
if (text.Length > 0)
{
_stringBytesWritten += text.GetBytesBigUni(_stringsBuffer.AsSpan(_stringBytesWritten));
}
if (_finalizeLayout)
{
_hashes[hash] = _stringsCount++;
}
}
public void FinalizeStrings(ref StaticGumpBuilder builder)
{
var startingIndex = builder._stringsCount;
var stringSlotOffsets = builder.StringSlotOffsets;
for (var i = 0; i < stringSlotOffsets.Length; i++)
{
var (hash, offset) = stringSlotOffsets[i];
if (hash != 0 && _hashes.TryGetValue(hash, out var index))
{
builder.WriteSlotIndex(offset, index + startingIndex);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
if (_finalizeLayout)
{
_hashes.Clear();
}
if (_stringsBuffer != _staticStringsBuffer)
{
STArrayPool<byte>.Shared.Return(_stringsBuffer);
}
}
}