Skip to content

Commit

Permalink
Performance tuning.
Browse files Browse the repository at this point in the history
  • Loading branch information
DJGosnell committed Nov 29, 2023
1 parent 81dcc5b commit a534841
Show file tree
Hide file tree
Showing 11 changed files with 1,410 additions and 179 deletions.
39 changes: 34 additions & 5 deletions src/DtronixCommon/Collections/Lists/DoubleList2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,23 @@ namespace DtronixCommon.Collections.Lists;
/// List of double with varying size with a backing array. Items erased are returned to be reused.
/// </summary>
/// <remarks>https://stackoverflow.com/a/48354356</remarks>
internal class DoubleList2 : IDisposable
public class DoubleList2 : IDisposable
{
[StructLayout(LayoutKind.Explicit)]
public struct ValType
{
[FieldOffset(0)] // 1 byte
internal double Value;
public double Value;
[FieldOffset(0)] // 4 bytes
internal int IntValue;
public int IntValue;

public static implicit operator ValType(double d) => new ValType() { Value = d };
public static implicit operator ValType(int d) => new ValType() { IntValue = d };

public override string ToString()
{
return $"Value: {Value}; Int: {IntValue}";
}
}


Expand Down Expand Up @@ -164,7 +170,7 @@ public ref ValType Get2(int index, int fieldStart)
/// <returns>Interger of the specified element field.</returns>
public int GetInt(int index, int field)
{
return (int)Get(index, field);
return _data![index * _numFields + field].IntValue;
}

/// <summary>
Expand Down Expand Up @@ -219,7 +225,6 @@ public int PushBack()
public int PushBack(ReadOnlySpan<ValType> values)
{
int newPos = (InternalCount + 1) * _numFields;

// If the list is full, we need to reallocate the buffer to make room
// for the new element.
if (newPos > _data!.Length)
Expand All @@ -238,6 +243,30 @@ public int PushBack(ReadOnlySpan<ValType> values)
return InternalCount++;
}

/// <summary>
/// Inserts an element to the back of the list and adds the passed values to the data.
/// </summary>
/// <returns></returns>
public int PushBack(scoped ref ValType values, int count)
{
int newPos = (InternalCount + 1) * _numFields;
// If the list is full, we need to reallocate the buffer to make room
// for the new element.
if (newPos > _data!.Length)
{
// Use double the size for the new capacity.
int newCap = newPos * 2;

// Allocate new array and copy former contents.
var newArray = new ValType[newCap];
Array.Copy(_data, newArray, _data.Length);
_data = newArray;
}
MemoryMarshal.CreateSpan(ref values, count).CopyTo(_data.AsSpan(InternalCount * _numFields));

return InternalCount++;
}

/// <summary>
/// Removes the element at the back of the list.
/// </summary>
Expand Down
Loading

0 comments on commit a534841

Please sign in to comment.