In a chess AI program, I have a function that has to do and then undo a move.
In order to do this, I need to save a backup of a bunch of arrays containing data about the current situation on the board (like where the pieces are, which pieces are under attack or if a king is in check, for example), then make the move and finally reset the arrays.
The code I'm using is like this:
int[] piecesBackup = pieces.Clone() as int[];
MakeMove();
pieces = piecesBackup.Clone() as int[];
// I've also tried this
int[] piecesBackup = new int[pieces.Length];
pieces.CopyTo(piecesBackup, 0);
MakeMove();
pieces = new int[piecesBackup.Length];
piecesBackup.CopyTo(pieces, 0);
This code is repeated thousands of times and it takes very long to do so. I suspect that the time consuming operation here is the cloning/copying operation.
I can't think of any better approach to this problem: is this really the only way to copy the contents of an array? Is there any way I could simply use int[] piecesBackup = pieces
and then pieces = piecesBackup
?