Why not use for(int i=0; i< v.size();i++){}?

For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:

For Loop

  1. int i = 0 is an assignment and creation (2 operations)
  2. i get size, check value of i, and compare (3 operations)
  3. i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
  4. 7/8 operations in total, each time the loop runs through

While Loop

  1. where an enumeration or iterator uses a while(){}
  2. while(v.hasNext()) has next true or false (1 operation)
  3. while(v.hasMoreElements()) has more true or false (1 operation)
  4. Only one operation per repeat of this loop

Comments are closed.