This discussion is archived
6 Replies Latest reply: Jun 15, 2013 4:38 AM by xStardust! RSS

For loop condition, semantics, and performance

xStardust! Newbie
Currently Being Moderated

Hello there !

 

During a programming exam, I wrote something like this:

 

public int indexOf(int element) {

   

     for (int i = 0; i < array.length; ++i) {

 

          if (array[i] == element) {

 

               return i;

 

          }

 

     }

 

     return -1;

   

}

 

Basically, this code scans through an array to find the index of an element.

 

The teacher told me that such a construction should be avoided, because of how for-if compiles. What I wrote also violates the semantics of the for loop, because a for loop is supposed to run a number of times that is known from the start.

 

So I asked the teacher what would be a better way to write this, and here's her suggestion:

 

// ...

int i;     // <-- edit

for (i = 0; i < array.length && array[i] != element; ++i);

// ...

 

This loop will also break before it ends but I guess there's no way around this problem.

But I have concerns about this suggestion when it comes to performances. I know from many books that for loops are faster than while loop, precisely because the number of iterations is known from the start, and processors have specific instructions for that kind of loop.

So my question is: Does adding a condition to the for loop hinders the performance?

Because if it does, perhaps I should just use a while loop to fix the early-break problem?

 

I'd like to know what is The Right Way™ to do this...

 

 

Thanks

  • 1. Re: For loop condition, semantics, and performance
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated

    xStardust! schrieb:

    The teacher told me that such a construction should be avoided,

    IMHO the teachers version is the one to avoid because its hard to read and includes an NOOP (no instruction after loop declaration). This is old fashioned C-Coding at its best...


    But I have concerns about this suggestion when it comes to performances.

    Do not optimize for performance unless you faced a performance problem and have identified the cause for the problem by measuring.

    Having said this I strongly beleave that both versions have same performance.

     


    bye

    TPD

  • 2. Re: For loop condition, semantics, and performance
    EJP Guru
    Currently Being Moderated

    > The teacher told me that such a construction should be avoided, because of how for-if compiles.

     

    Rubbish. The teacher's version wont' even work. The value of 'i' isn't available when the loop terminates. And when you fix that, it compiles almost identically to yours except that it's longer.

     

    > What I wrote also violates the semantics of the for loop, because a for loop is supposed to run a number of times that is known from the start.

     

    It doesn't violate any such thing. First, array.length is a constant, so the number of times is known from the start. Second, there is no such semantic requirement in the first place. The compiler enforces the static semantics of Java: if you had them wrong, it would have told you; and the JVM implements the dynamic semantics, ditto.

     

    > I know from many books that for loops are faster than while loop, precisely because the number of iterations is known from the start

     

    You don't know any such thing. The test-expression in a for loop is entirely arbitrary. The number of iterations doesn't have to be known from the start. And it can be known from the start in a while-loop. Consider

    int i = 0;
    while (i++ < 10) {}
    

    > and processors have specific instructions for that kind of loop.

     

    This is Java. We are talking about the JVM. We are several layers away from the processor.

     

    It seems to me that either your teacher doesn't know what he/she is talking about, which is surprisingly prevalent, or that he/she is purely quibbling about coding style. Do whatever you have to do to get the marks, but don't pay too much attention to this sort of nonsense. Unfortunately it looks like you're going to encounter a lot more of it before you're through. Stand by for not being allowed to catch EOFException, for example.

  • 3. Re: For loop condition, semantics, and performance
    xStardust! Newbie
    Currently Being Moderated

    Rubbish. The teacher's version wont' even work. The value of 'i' isn't available when the loop terminates. And when you fix that, it compiles almost identically to yours except that it's longer.

     

    My bad! int i is actually outside the for loop

     

    I agree with the empty for loop body not being a good idea, it looks ugly and nonsense-ish to me, plus NetBeans yells at me if I do that.

     

    My teacher knows what she's talking about, and it was purely a coding style issue. Other concerns were mine. We've been taught the for loop as being similar to the mathematical sum expression (sigma), so it seemed weird to me to break the loop before it ends since it's something we don't do in math.

    I'm only in first year so my questions are probably stupid.

     

    Now, of course I'll do whatever I have to do to get the marks, but apart from that, I'm really concerned about doing things as right as possible when working on my own code.

    That's why I was asking what is the "best" way to go with this problem.

    What would an expert do instinctively? This is what I'd like to know.

     

    Putting a second condition in the for loop seems harder to read to me.... And what if I have more conditions to deal with?

    Teachers tell us to try and have as less returns as possible, which seems very reasonable to me, as more exit points complicate the code. This is also one of the reasons why she told me to avoid my for-if-return construction.

    ...but obviously I can't let the loop scan through the rest of the array once it has found what it's looking for.

    So I'm really confused about what to do.

     

    Anyways, thanks for your replies, it helped

  • 4. Re: For loop condition, semantics, and performance
    gimbal2 Guru
    Currently Being Moderated

    xStardust! wrote:

     

    Rubbish. The teacher's version wont' even work. The value of 'i' isn't available when the loop terminates. And when you fix that, it compiles almost identically to yours except that it's longer.

     

    ...but obviously I can't let the loop scan through the rest of the array once it has found what it's looking for.

    9/10 times you can and it is only a performance concern to break out with either a return or a break keyword. If there are not so many elements in the array (dozens are still not many) - who cares it loops through the entire thing to find one element?

     

    But then again: you -can- break out early with only a single statement, so why not use that?

  • 5. Re: For loop condition, semantics, and performance
    rp0428 Guru
    Currently Being Moderated

    >

    The teacher told me that such a construction should be avoided, because of how for-if compiles

    >

    Nonsense! Neither you nor your teacher will know how 'for-if compiles'. That depends on the compiler. You should NEVER write code based on how you think a compiler might work. You not only won't know how the compiler makes it decisions but you also won't always have any control over what compiler is even being used.

     

    Putting a second condition in the for loop seems harder to read to me.... And what if I have more conditions to deal with?

    Teachers tell us to try and have as less returns as possible, which seems very reasonable to me, as more exit points complicate the code. This is also one of the reasons why she told me to avoid my for-if-return construction.

    ...but obviously I can't let the loop scan through the rest of the array once it has found what it's looking for.

    So I'm really confused about what to do.

     

    You have overlooked something about the example you said your teacher provided. If you don't return from the loop then you need to add ANOTHER test after the loop to determine what value to return. You want to return -1 IF the loop did NOT find the element but how are you going to know if an element was found?

     

    The loop conditions should specify the requirements for executing the loop. The loop itself should be used to search for the array element and any other work that needs to be performed. Your concern about having 'more conditions to deal with' is valid. You want to write code that is modular, scalable and easy to understand. You can't anticipate what future requirements might be. If a future requirements modifies WHEN the loop should be executed then you change the loop conditions. If the requirement modifies the WORK to be done you modify the loop contents.

     

    Your method should return when its work is completed and you have determined the value that needs to be returned. For your example that is when the loop finds the element being looked for so that is where a RETURN should be. If you need to do additional work AFTER finding the element then the loop code should set a flag (e.g. 'found = true') and then 'break'. The code AFTER the loop would test the flag and act accordingly.

  • 6. Re: For loop condition, semantics, and performance
    xStardust! Newbie
    Currently Being Moderated

     

    Your method should return when its work is completed and you have determined the value that needs to be returned. For your example that is when the loop finds the element being looked for so that is where a RETURN should be. If you need to do additional work AFTER finding the element then the loop code should set a flag (e.g. 'found = true') and then 'break'. The code AFTER the loop would test the flag and act accordingly.

    Makes perfect sense. I also had the curiosity to look into the JDK source code and they did it like this.

    Ok now I know what to do, thank you everyone !