Sunday, January 29, 2012

Index-based loops vs Iterator loops

First lets look at two examples of what the difference is between these two types of loops. My choice language for this exercise is Java.




Index-based loop:
for (int i = 0; i < sampleArray.length; i++){
    System.out.println(sampleArray[i]);
}
Full compilable code.


Iterator loop:
for (int item : sampleArray){
    System.out.println(item);
}


So, other than just having a different structure, what makes the both of these so different? For starters, we need to know that the traditional loop is a type of basic control abstraction, and it's actually a branching operation behind the scenes. We can say the index-based loop is a form of syntactic sugar, which is a way to make something appear simpler, for a branching instruction. This also means that the iterator loop is syntactic sugar for the traditional loop. The difference between the two is that the iterator loop provides a better abstraction for programmers. The problem with the traditional index-based loop is that there are so many bad practices that could be implemented when coding an index-based loop. This isn't always a huge  problem, but when it comes to code will last, and is maintainable, it's a problem. The iterator loop is managed code, and will work no matter if the size of the array changes or not. Although this is true for iterating through the whole array and not just a subset.

No comments:

Post a Comment