'Fixed' for loop - what is more efficient?

Posted by pimvdb on Stack Overflow See other posts from Stack Overflow or by pimvdb
Published on 2011-01-16T11:36:33Z Indexed on 2011/01/16 11:53 UTC
Read the original article Hit count: 257

Filed under:
|

I'm creating a tic-tac-toe game, and one of the functions has to iterate through each of the 9 fields (tic-tac-toe is played on a 3x3 grid). I was wondering what is more efficient (which one is perhaps faster, or what is the preferred way of scripting in such situation) - using two for nested loops like this:

for(var i=0; i<3; i++) {
 for(var j=0; j<3; j++) {
  checkField(i, j);
 }
}

or hard-coding it like this:

checkField(0, 0);
checkField(0, 1);
checkField(0, 2);
checkField(1, 0);
checkField(1, 1);
checkField(1, 2);
checkField(2, 0);
checkField(2, 1);
checkField(2, 2);

As there are only 9 combinations, it would be perhaps overkill to use two nested for loops, but then again this is clearer to read. The for loop, however, will increment variables and check whether i and j are smaller than 3 every time as well.

In this example, the time saving at least might be negligible, but what is the preferred way of coding in this case?

Thanks.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about algorithm