0

I have seen using For loop in these two fashions. Is there any positive aspect of using ! instead of using < ? Which one is faster?

for (i = 0; i != imax; ++i)
{
}

or

for (i = 0; i < imax; ++i)
{
}
Mehdi
  • 211
  • 2
  • 11
  • 3
    they mean two different things – bsoist Jul 08 '14 at 01:11
  • @bsoist but they only have different actions if the incrementing of `i` is not affected inside the loop and only incremented by 1 like in the example, right? – Brad Jul 08 '14 at 01:13
  • @Mehdi What if your `for` was `for (i = 0; i != imax; i+=3)` and imax was 20, what do you think that would happen? – Prix Jul 08 '14 at 01:13
  • @Brad you are correct, so if you are careful using it, it might work as expected, BUT I doubt there is any benefit, so I would opt for code that is clearer in it's intent. If you want to see if there is a real performance benefit, you could benchmark it, but I highly doubt it's worth sacrificing clarity. – bsoist Jul 08 '14 at 01:16
  • @Prix , yes, you are right. what about if incremented by 1 ? My code is full of For loops and are very slow, I need a way to increase calculation speed even 1%. – Mehdi Jul 08 '14 at 01:17
  • @Mehdi: why do you think a loop exit condition is the thing that is slow? You don't optimize random things in your code, but the things that are actually slow. – zerkms Jul 08 '14 at 01:18
  • @Mehdi without looking at what your code is actually doing we can't tell you why its slow. – Prix Jul 08 '14 at 01:18
  • 3
    This is not the way to make your loop faster. The code inside is substantially slower than the method used for checking integer equality. – Brad Jul 08 '14 at 01:19
  • 1
    The reason to choose one or the other is because of intent and as a result of this, it increases readability. see this link http://programmers.stackexchange.com/questions/70996/versus-as-condition-in-a-for-loop – bumbumpaw Jul 08 '14 at 01:21
  • @Prix , actually, I am trying to use performance & diagnostic ability of VS but have difficulty of understanding its comments. For example, I have two For loop inside each other and it gives me 39% of inclusive for internal loop at increment section ! What does that mean? – Mehdi Jul 08 '14 at 01:27
  • 1
    "full of for loops" may be a code smell... can linq benefit you in any way? if you have "for" in a "for" in a "for", you will be better off refactoring and trying out linq over a for. are your for loops doing calculations? setting data? getting data? populating lists? like Prix said, its hard to guess whats slow if we dont know what you want to accomplish... – Andy Danger Gagne Jul 08 '14 at 01:33
  • @AndyDangerGagne I have not use LINQ up to know and need to check what is its ability. My code is for scientific purpose so as you said For loops are getting data and calculate and save them. What is the advantage of LINQ ? – Mehdi Jul 08 '14 at 01:39
  • And I found this question which they say LINQ is slower than For loop: http://stackoverflow.com/questions/3156059/linq-statement-faster-than-foreach-loop – Mehdi Jul 08 '14 at 01:45
  • 1
    @Mehdi yes, linq may introduce some overhead... But it also depends on whats going on in your code. linq introduces a "Delayed execution" which will allow you to spin up some where clauses and search a subset of data. It wont xecute your query or action until the end. It also allows you to join two sets of collections via Union clause and search that. I would definitely need some benchmarking on your end to see if your for loops will outperform the linq. – Andy Danger Gagne Jul 08 '14 at 01:52
  • If you iterate over an array, `for(int i = 0; i < array.Length; i++)` could be significantly faster since the JITter has hardcoded that pattern to omit array bounds checks. Of course this only matters if the body of the loop is cheap. – CodesInChaos Jul 09 '14 at 12:20

6 Answers6

7

Is there any positive aspect of using ! instead of using < ?

It is highly unlikely for this case. For the given example it's more semantic to use the latter because it expresses your real intentions.

Which one is faster?

You should never write your code with that in mind. Do it right, then do it fast. The better designed and maintainable your code originally is - the easier it will be to optimize it (if it ever will need to be optimized).

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • -1 for the never. For most code it doesn't matter, but in high performance code, differences like this can matter. – CodesInChaos Jul 09 '14 at 12:22
  • @CodesInChaos: people who should care about that will never follow my advice - they know it already better than me. So I'm still standing on my point: for the audience that this answer is addressed - it's a strong "never". – zerkms Jul 09 '14 at 20:10
4

Which one is faster?

To answer this question, we need to go to lower level of programming and even to the machine level as it cannot be answered through higher level of programming with technical explanation.

First of all, lets see how assembly language performs loops. Before I start, I want to tell that I have used many sources and actual implemnetation of Assembly language, Architecture of Flags, Processor, etc vary. I don't want to write so much of assembly code so I am adding screenshots from http://www.cs.colostate.edu/~fsieker/misc/CtoLC3.html

In image given below, you can see how conditional logical expression are converted into numeric expression. Similar thing happens for Loops. LHS of numeric expression is what performed at machine level by an ALU (Arithmetic Logical Unit) of processor. Depending upon result of LHS i.e. (a-b), conditional jumps (branching) is performed

enter image description here

Implementation of loops is given below:

enter image description here

For all conditions value of expression (a-b) is calculated by processor's ALU. ALU never performs subtraction, it can only do addition. It simply adds the two's complement of number that is being subtracted to the first number.

For example, when 'a' & 'b' are fed to ALU, it adds 'a' with 2's compliment of 'b' and gives output. Along with the result it raises corresponding 'Flags' as shown below (ref. https://courses.engr.illinois.edu/ece390/books/labmanual/assembly.html )

enter image description here

Depending upon the values of various flag values, branching is performed. Example is shown below:

enter image description here

You can see no matter what sign one is using, whether '!=', '>', '>=', processor always performs '(a-b)'. Depending upon result 'Flags', 'Program Counter' gets incremented using 'Digital Logic' to fetch next instruction, which can either be inside the loop body or outside the loop body depending upon conditions. These two sources can give you little bit info about machine level implementation (however, its not necessary but only if you want do dive further).

http://minnie.tuhs.org/CompArch/Tutes/week02.html

http://people.tamu.edu/~akshitdayal/468/MIPS-Implementation.pdf

So, it does not makes it fast. However, second implementation 'i < imax' is correct if logical condition to be met is 'i less than imax' and 'i != imax' is correct if logical condition is 'i not equal to imax'. In your case its not affecting, but suppose, if increment is not ++i or i++ but i = i + 2 and condition is 'i less than imax', then there are chances that it becomes an infinite loop if 'i != imax' is used. Coding should always be the manifestation of basic logical reasoning behind it. :)

sunny
  • 783
  • 9
  • 11
2

None of them are actually "faster" . It depends on the value of "imax " .For example ,in your first code , if "imax" doesn't equal zero (less than zero) , the 'for' loop will never stop

  • I think you mean imax less than zero. Depending on the hardware, there might be a slight difference in speed, but not worth worrying about if the loop has to correctly handle imax less than zero. – Zenilogix Jul 08 '14 at 01:37
2

Unlikely there is any measurable difference in execution speed.

But there is significant difference in speed of reading such piece of code. You wrotefor loop in unusual way which indicates to reader that there is something special about this particular loop. It make reading of such code more time consuming (need to understand what is the reason behind special version of code, if any) and as result making it harder to improve.

Usual way of writing for loop in C#:

for (i = 0; i < imax; i++)
{
   ....
}

Pretty much any other way of writing the loop should cause you as developer stop and spend extra time to read and understand why original writer did something special for that particular loop.

Note: "usual" may vary between projects, so if code you use consistently happen to use other style like Yoda notation align your code with the rest go ahead and use ++i or even imax > i as long as it matches style of the rest of the code.

Note 2: My post turned out to be exact copy of https://softwareengineering.stackexchange.com/questions/70996/versus-as-condition-in-a-for-loop which covers C++ reasoning in great detail. Fortunately C# have native iteration with foreach and there is no need to be concerned with "code will look the same between integer and iterator indexing".

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

Unfortunately there is no advantage in speed. However you could argue back and forth for which looks better, or is safer; especially if someone comes along and adds an extra ++i in the middle of the for loop in 6 months.

Brent
  • 1,378
  • 2
  • 16
  • 30
1
for (i = 0; i != imax; ++i)

Is prone to bugs introduced by programmers not paying enough attention. Most people are used to see this version around:

for (i = 0; i < imax; ++i)

and as such, they will probably parse it quickly and say "yup, that's a for from 0 to imax - 1".

Having the thought that i will stay inside [0, imax) in mind, they might just write a quick hack to solve a hypothetical problem, basically changing the value of i inside the loop. Then they notice that in some cases i becomes greater or equal to imax and the loop keeps on going.

As for speed, no, that should not be a factor to consider.