Home > database >  More efficient way to check if a value is included in an array?
More efficient way to check if a value is included in an array?

Time:12-20

Writing a game that does lots of comparisons, and it's lagging. I'm trying to speed it up, and this particular chunk of code is run thousands of times every frame, for different values of x y and z. Is there a better way to check if the values of x y and z are valid in the array? (java)

if (x >= 0 && x < blocksArr.length && y >= 0 && y < blocksArr[x].length && z >= 0 && z < blocksArr[x][y].length && blocksArr[x][y][z])

I've tried checking if blocksArr[x][y][z] != null and checking if blocksArr[x][y][z] != undefined but neither give results.

CodePudding user response:

I don't know java but in general, I would expect the following to be at least as fast, possibly faster. Your compiler may do something like this anyway so it might not be faster. You can split the 'If' statement up so that it will do fewer lookups. Sorry, but I'll have to write it as c code. You can get the idea and translate to java.

if (x >= 0 && y >= 0 && z >= 0 && x < blocksArr.length) {
  if (y < blocksArr[x].length && z < blocksArr[x][y].length && blocksArr[x][y][z]) {
    .....
  }
}

Assuming user16320675 is correct about the evaluation order, you could use one 'if' statement. I don't know how the java compiler works.

if (x >= 0 && y >= 0 && z >= 0 && x < blocksArr.length && y < blocksArr[x].length && z < blocksArr[x][y].length && blocksArr[x][y][z]) .....

CodePudding user response:

 Use below logic

   if(isValid()){
    //Remaining code
    }
    
    public bool isValid(){
    // if blocksArr[x][y][z] != null
    // Multiple condition check here if all condition satisfy then return true else return false 
    Return false;
    }
  • Related