Refactor allocation types and improve memory management
This commit renames `AllocationType` to `AllocationOption` across multiple files, enhancing clarity in memory allocation practices. Key updates include: - Modifications to the `UnsafeArray`, `ParallelNoiseBenchmark`, `Arena`, and `DynamicArena` classes to utilize the new `AllocationOption`. - Refactoring of the `AllocationManager` and `HashMapHelper` classes to support the new allocation strategy. - Removal of the `Misaki.HighPerformance.Mathematics` project reference, indicating a restructuring of dependencies. - Introduction of a new `MathUtilities` class for calculating the smallest power of two, aiding memory allocation strategies. These changes collectively improve code maintainability and clarity in memory management.
This commit is contained in:
68
Misaki.HighPerformance.Unsafe/Services/AllocationManager.cs
Normal file
68
Misaki.HighPerformance.Unsafe/Services/AllocationManager.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using Misaki.HighPerformance.Unsafe.Buffer;
|
||||
using Misaki.HighPerformance.Unsafe.Collections;
|
||||
|
||||
namespace Misaki.HighPerformance.Unsafe.Services;
|
||||
|
||||
public static unsafe class AllocationManager
|
||||
{
|
||||
private static DynamicArena _arena;
|
||||
private static bool _initialized;
|
||||
|
||||
private static readonly Lock _lock = new();
|
||||
|
||||
public static void Initialize(uint initialSize)
|
||||
{
|
||||
_arena = new DynamicArena(initialSize);
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
internal static T* Allocate<T>(uint size, uint alignSize, Allocator allocator, AllocationOption allocationType)
|
||||
where T : unmanaged
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
throw new InvalidOperationException("The AllocationManager has not been initialized.");
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
return allocator switch
|
||||
{
|
||||
Allocator.Temp => (T*)_arena.Allocate(size * (uint)sizeof(T), alignSize, allocationType),
|
||||
Allocator.Persistent => (T*)AlignedAlloc((nuint)(size * sizeof(T)), alignSize),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(allocator), "Invalid allocator type."),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
internal static void Free(void* ptr, Allocator allocator)
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
throw new InvalidOperationException("The AllocationManager has not been initialized.");
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (allocator == Allocator.Persistent)
|
||||
{
|
||||
AlignedFree(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Reset(bool clear = false)
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
throw new InvalidOperationException("The AllocationManager has not been initialized.");
|
||||
}
|
||||
|
||||
_arena.Reset(clear);
|
||||
}
|
||||
|
||||
public static void Dispose()
|
||||
{
|
||||
_arena.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user