I am trying to optimize a snake like game made in C# where I have an ArrayList that contains all the snake body parts stored. I need to be able to cut this ArrayList like if it was a deck of cards, where I would take the top part of the deck and make it the bottom one. This should help clarify.
01234 => 01 234 => 234 01 => 23401
This ArrayList can be as big as 300 elements and I need to make this operation as cheap as possible since this game is for mobile devices.
Using Array.Copy should be the fastest way to get there. But it requires you to use T[] array, not ArrayList.
public void CutTop<T>(this T[] source, int nbOfItemsToCut) {
if(source == null)
throw new ArgumentNullException("source");
var length = source.Length;
if(nbOfItemsToCut > length)
throw new ArgumentException("nbOfItemsToCut");
var temp = new T[nbOfItemsToCut];
Array.Copy(source, temp, nbOfItemsToCut);
Array.Copy(source, nbOfItemsToCut, source, 0, length - nbOfItemsToCut);
Array.Copy(temp, 0, source, length - nbOfItemsToCut, nbOfItemsToCut);
}
Since you want to move items from beginning to end, a LinkedList<T> might be a good choice here, assuming you don't frequently access random elements within the list:
public void MoveToEnd<T>(LinkedList<T> list, int count)
{
if(list == null)
throw new ArgumentNullException("list");
if(count < 0 || count > list.Count)
throw new ArgumentOutOfRangeException("count");
for (int i = 0; i < count; ++i)
{
list.AddLast(list.First.Value);
list.RemoveFirst();
}
}
var snake = new[] { 0, 1, 2, 3, 4 };
var list = new LinkedList<int>(snake);
Console.WriteLine(string.Join(" ", list)); // 0 1 2 3 4
MoveToEnd(list, 2);
Console.WriteLine(string.Join(" ", list)); // 2 3 4 0 1
In any case, I would suggest you measure the time it takes to perform this operation in your current implementation to see if it's actually necessary to optimize this part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With