-1

My co-worker and I discussing about the code readability on simple loops. Suppose a method takes an integer parameter and does some operation on the elements of an array depending on the parameter. e.g

For the sake of simplicity, assume array bounds are negligible and there is no error generated by the codes I presented below.

function doSomeOp(targetIndex) {
  for(var i = targetIndex + 5; i < someArray.length; i++) {
    someArray[i] = 42;
  }
}

as opposed to;

function doSomeOp(targetIndex) {
  for(var i = targetIndex; i < someArray.length; i++) {
    someArray[i + 5] = 42;
  }
}

Is there any advantage to define the loop parameter to simpler values like "0", "targetIndex", "array.length" and then define business logic when using that loop parameter?

1
  • 3
    Side Note: The worst issue with the example code above (once the bug Nathan Cooper aready pointed out in his answer is fixed) is not how the offset is added, but the naming of the parameter.
    – Hulk
    Commented Oct 28, 2015 at 9:25

1 Answer 1

4

"For the sake of simplicity, assume array bounds are negligible and there is no error generated by the codes I presented below."

So You've introduced an error into your program by forgetting to add the -5 because the second needs it in two places.

Also, this is just imho, but the first loop works more like my mind works when interacting with loop (and works more like if you changed it out for an iterator).

To the extent the this incredibly marginal issue matters, the first is better.

// The second fixed:
function doSomeOp(targetIndex) {
  for(var i = targetIndex; i < someArray.length - 5; i++) {
    someArray[i + 5] = 42;
  }
}
3
  • Totally Agree with @Nathan. In addition to what he said, why do you want to do an operation of i+5 in every loop? It's an extra addition performed which is not needed at all (if you use 1st approach). Also it's even better if you can store the value of "someArray.length"/"someaArray.length -5" in a variable and then use it in a for loop. I am not sure about other languages but in C#, it will call the get of length property for every iteration of for loop and also it will perform someArray.length - 5 computation (if you used 2nd approach) in every iteration Commented Oct 28, 2015 at 10:39
  • @GawdePrasad Not relevent to asker, so we can chat if you want to discuss. In C# use Array.Length in the loop because it's basically an inlined non caculation, and access in in a loop with be optimised more agressivily by the complier than your hoisting.
    – Nathan
    Commented Oct 28, 2015 at 10:59
  • May be true for Array as arrays have fixed length but for Lists, ArrayList etc which can have variable length, Length will be called for every iteration (coz the length can change if user deletes an item from list) Commented Oct 28, 2015 at 11:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.