Need help optimizing your search

I am new to programming and I need help with optimization. Basically part of my method:

for(int i = 0; i < Tiles.Length; i++) { x = Tiles[i].WorldPosition.x; y = Tiles[i].WorldPosition.y; z = Tiles[i].WorldPosition.z; Tile topsearch = Array.Find(Tiles, search => search.WorldPosition == Tiles[i].WorldPosition + new Vector3Int(0,1,0)); if(topsearch.isEmpty) { // DoMyThing } } 

So, I'm looking for a tile in a position that is 1 unit above the current tile. My problem is that it takes 0.1 s for the whole method, which leads to a slight upward movement. Without Array.Find method is 0.01 s.

I also tried with the for loop, but still not a very good result, because I need 3 more checks for the bottom, left and right.

Can someone help me and show me a way to get quick results? Maybe I should go with something like slicing?

+6
source share
3 answers

You can create a 3-dimensional array so that you can search for a tile in a specific place simply by looking at that in Tiles[x, y + 1, z] .

You can then iterate over your data in 2 loops: one to create Tiles and one to perform the checks that you do in your code above, which should be as follows:

 for(int i = 0; i < Tiles.Length; i++) { Tile toFind = Tiles[Tile[i].x, Tile[i].y + 1, Tile[i].z]; if (toFind != null) ... } 

You will need to measure the array so that you have 1 extra row in y, so that Tiles[x, y + 1, z] does not throw an index exception outside the range.

+9
source

By adding Roy to the solution , if the space is not continuous, however, you can put the WorldPosition hash code (x, y and z coordinates) for good use here.

I mean, you can override WorldPosition GetHashCode your own implementation:

 public class WorldPosition { public int X; public int Y; public int Z; public override int GetHashCode() { int result = X.GetHashCode(); result = (result * 397) ^ Y.GetHashCode(); result = (result * 397) ^ Z.GetHashCode(); return result; } } 

See Why is "397" used to override GetHashCode ReSharper? for an explanation.

Then you can put your tiles in Dictionary<WorldPosition, Tile> .

This will allow you to quickly search for dict[new WorldPosition(x, y, z + 1)] , etc. Dictionaries use a hash code for keys, so it will be fast.

+4
source

First, as @Roy suggested, try storing the values โ€‹โ€‹in an array so that you can access them with the coordinates x, y, z,

Another thing you can do is change the search to

 Tile topsearch = Array.Find(Tiles, search => search.WorldPosition.x == Tiles[i].WorldPosition.x && search.WorldPosition.y == (Tiles[i].WorldPosition.y + 1) && search.WorldPosition.z == Tiles[i].WorldPosition.z) 

It can be faster, depending on how many fields your WorldPosition has

0
source

All Articles