-3

whats the cost of transforming the following loop

for ( 0 to n) {
    operations of step 1
    operations of step 2
    operations of step 3
}

to the following 2 for loops

for ( 0 to n) {
    operations of step 1
    operations of step 2
}

for (0 to n) {
    operations of step 3
}

considering that the operations are not simple short statements.

the benefit of the 2 loops method would be easier on the programmer and code difficulty, whats the tradeoff on the performance/time cost?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188

2 Answers2

2

This is not the way to go if you want to make the code more readable. If things must be done in a loop, then leave them in this loop. Splitting the code into two loops changes the order of execution.

You can enhance readability by extracting the complex code to methods. Especially when you choose speaking method names. Avoid names like ExecuteStep1, ExecuteStep2, etc.

for (int i = 0; i < n; i++) {
    var data = ReadData(i);
    var transformed = TransformData(data);
    SaveTransFormedData(i, transformed);
}

In the real code you would replace the generic Data by a concrete term like Bookings.

Note that I/O operations are measured in milliseconds while pure code operations are measured in nanoseconds. There is a factor of one million between the two! So, calling a few additional methods will not hurt you.

Another option is to avoid this loop completely is to move it to these methods and to let these methods accept and return IEnumerable<T> and make them extension methods. Then you can write:

ReadData().TransformData().SaveTransFormedData();

See:

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

In first scenario you can keep the iteration variable everytime you doing operations with it. And you need to iterate loop twice in the second scenario. So, it seems to take more time to perform operations. Furthermore, it decrease code readability, cause it can be confusing about why the same loops separated.

Elvis
  • 108
  • 1
  • 7