Increment the neighbors of a cell in a matrix Let's say you want to increment the cells around the position (x,y) in a square matrix m of size T.

I've written the same code in a few languages. Here's the JS syntax version :

if (x&gt;0) {
    if (y&gt;0) m[x-1][y-1]++;
    m[x-1][y]++;
    if (y&lt;T-1) m[x-1][y+1]++;
}
if (y&gt;0) m[x][y-1]++;
if (y&lt;T-1) m[x][y+1]++;
if (x&lt;T-1) {
    if (y&gt;0) m[x+1][y-1]++;
    m[x+1][y]++;
    if (y&lt;T-1) m[x+1][y+1]++;
}


I don't like this kind of code, those tests look redundant. What bothers me is less the clarity of the code than the fact it has to do so many times the same checks.

But I don't see anything better. Am I just missing an obvious solution or is there nothing better with the branching toolset we have ? A slower code isn't acceptable as an answer, performance is the essence of the question.
Like Simon I would store the directions into a data structure, though I would probably hard code it

//Array Index Constants
var X = 0 , Y = 1; 
//All 8 neighbours ( vectors )
var vectors = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];


The fun thing about JavaScript is that there is no ArrayIndexOutOfBoundsException in JavaScript, requesting a value out of bounds returns undefined.

So, now, you can go for 

for( int i = 0 ; i &lt; vectors.length ; i++ ){
  var vector = vectors[i];
  if( m[x+vector[X]] &amp;&amp; m[x+vector[X]][y+vector[Y]] !== undefined )
    m[x+vector[X]][y+vector[Y]]++;  
}


I did use for m[x+vector[X]] a falsey comparison, if the row X was defined it would pass the falsey evaluation ( it would be an Array ). For m[x+vector[X]][y+vector[Y]] I compared to undefined, since 0 is a realistic, acceptable value which would evaluate as false.

If I had to do a lot of matrix magic, then I would have a dedicated function to check whether a point is part of the matrix. And a dedicated function to add a vector to a point.