Skip to content

Instantly share code, notes, and snippets.

@JKamsker
Created October 19, 2017 21:36
Show Gist options
  • Save JKamsker/e4168fc921aa9cf5e32910f2160482e0 to your computer and use it in GitHub Desktop.
Save JKamsker/e4168fc921aa9cf5e32910f2160482e0 to your computer and use it in GitHub Desktop.
public class FastList<T>
{
private readonly List<T> _internalList = new List<T>();
public int Count => _count;
private int _count;
private int _freeIndex;
public T this[int index] => _internalList[index];
public int Add(T input)
{
while (true)
{
if (_freeIndex == _count)
{
_internalList.Add(input);
return _count++;
}
else
{
if (_internalList[_freeIndex] == null || _internalList.Equals(default(T)))
{
_internalList[_freeIndex] = input;
return _freeIndex++;
}
else
{
_freeIndex++;
}
}
}
}
public void Remove(int index)
{
_internalList[index] = default(T);
Interlocked.Exchange(ref _freeIndex, index);
}
public bool Exists(int index)
{
if (_count < index || _internalList[index] == null || _internalList[index].Equals(default(T)))
return false;
return true;
}
public bool TryGetValue(int key, out T value)
{
if (!Exists(key))
{
value = default(T);
return false;
}
else
{
value = _internalList[key];
return true;
}
}
public bool TryPickValue(int key, out T value)
{
if (!Exists(key))
{
value = default(T);
return false;
}
else
{
value = _internalList[key];
Remove(key);
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment