2

Consider this simple problem:

Suppose I have a 1x4 array. I have to add 5 to each of its element. Then is it advisable to use a loop. Removing the size of code factor & good organization of code, is there any other reason why I should use a loop? Wont it take more time than executing 4 straight lines of code wherein I add 5 to each element as the control has to go back over 5 times & change the value of loop variable? What if we consider a 1x2 array? Then we dont even have the size problem, both types of code would consist of 2 lines.

Although I am tagging this question in C, I would like to know about this in other languages too.

gopi1410
  • 6,567
  • 9
  • 41
  • 75
  • Look at [this other example](http://stackoverflow.com/a/11639305/597607) of what a compiler does, and stop worrying about low-level optimizations. I almost all cases the compiler will fix it for you. – Bo Persson Aug 11 '12 at 12:02

3 Answers3

4

You don't really need to worry about this. Write the way you find it easier to read, then let the compiler decide whether it finds it necessary to perform some loop unrolling optimization. Trust compiler vendors, their developers are very good at understanding these kinds of optimization-related stuff...

  • ah.. didn't knew that compilers optimized these kind of issues :) – gopi1410 Aug 11 '12 at 11:58
  • 2
    @gopi1410 you would be extremely surprised if you knew how many optimizations e. g. GCC does. For example, it even replaces a call to printf() with a call to puts() if the printf() call only has a constant string argument with no format parameters. –  Aug 11 '12 at 12:05
1

This is a micro optimization. If you don't have to save on the cycle level you don't have to worry unrolling such a loop. The important factor is readability and maintainability. For a loop of two iterations I don't think you add anything in readability by adding a loop.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

You shouldn't bother too much about performance of the code when you are taking such minor examples... Code the way it is easier to understand...

Using a loop provides you a way to scale the example without major changes everywhere.

Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
  • I am not bothered about the performance of this case, I know it wont matter on execution time whichever way I tool. All I wanted to know was which would be preferred in case of large test cases. – gopi1410 Aug 11 '12 at 12:01