I am working on optimizing a Wator program. I have a specific question about code, if you are familiar with it. There is a function which takes most of the time. I need your help to improve this particular part of the code.
// find all neighbouring cells of the given position that contain an animal of the given type
public int GetNeighbors(Type type, Point position) {
int neighborIndex;
int i, j;
// counter for the number of cells of the correct type
neighborIndex = 0;
// look up
i = position.X;
j = (position.Y + Height-1)%Height;
// if we look for empty cells (null) we don't have to check the type using instanceOf
if ((type == null) && (Grid[i, j] == null)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
} else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
// using instanceOf to check if the type of the animal on grid cell (i/j) is either a shark of a fish
// animals that moved in this iteration onto the given cell are not considered
// because the simulation runs in discrete time steps
if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
}
}
// look right
i = (position.X + 1) % Width;
j = position.Y;
if ((type == null) && (Grid[i, j] == null)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
} else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
}
}
// look down
i = position.X;
j = (position.Y + 1) % Height;
if ((type == null) && (Grid[i, j] == null)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
} else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
}
}
// look left
i = (position.X + Width - 1) % Width;
j = position.Y;
if ((type == null) && (Grid[i, j] == null)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
} else if ((type != null) && (type.IsInstanceOfType(Grid[i, j]))) {
if ((Grid[i, j] != null) && (!Grid[i, j].Moved)) {
neighbors[neighborIndex] = new Point(i, j);
neighborIndex++;
}
}
return neighborIndex;
}