participate


Java Programming [Archive] - return Vs break in while loop ; for effeciency
<<   Back to Forum  |   Give us Feedback
This topic has 23 replies on 2 pages.    1 | 2 | Next »
intelligentxjini
Posts:94
Registered: 11/25/02
return Vs break in while loop ; for effeciency   
Feb 19, 2003 12:36 PM

 
Can any one explain me which of the following two is more effecient and why.

/
Situation is searching in a Vector for an element.
/

Iterator i = vector.iterator();

while(i.hasNext())
{ Object obj = i.next();
if(objequals(search_obj))
{
return obj;
}
}

/////// or //////
Object cought_object;
while(i.hasNext())
{ Object obj = i.next();

if(objequals(search_obj))
{
cought_object = obj;
}

return cought_object;
}


waiting for response.
Nas.
 
pervel
Posts:2,091
Registered: 4/20/97
Re: return Vs break in while loop ; for effeciency   
Feb 19, 2003 12:42 PM (reply 1 of 23)  (In reply to original post )

 
Isn't the answer pretty obvious? The second version does a lot more than the first version: declares a variable, assigns to the variable, fetches the value from the variable before returning.

Although, the difference between the two versions are probably almost not detectable in practice, you should favor the first version because it is better coding style.
 
intelligentxjini
Posts:94
Registered: 11/25/02
Re: return Vs break in while loop ; for effeciency   
Feb 19, 2003 12:49 PM (reply 2 of 23)  (In reply to #1 )

 
What if i use Break
actually i forgot tp put the break in th efirst post.
Can any one explain me which of the following two is more effecient and why.

/
Situation is searching in a Vector for an element.
/

Iterator i = vector.iterator();

while(i.hasNext())
{ Object obj = i.next();
if(objequals(search_obj))
{
return obj;
}
}

/////// or //////
Object cought_object;
while(i.hasNext())
{ Object obj = i.next();

if(objequals(search_obj))
{
cought_object = obj;
break;
}

return cought_object;
}
 
rvflannery
Posts:785
Registered: 4/25/00
Re: return Vs break in while loop ; for effeciency   
Feb 19, 2003 1:07 PM (reply 3 of 23)  (In reply to #2 )

 
use the code tags to format your posts- it will make them a lot easier to read: http://forum.java.sun.com/faq.jsp#format
 
asquithea
Posts:1,212
Registered: 2/17/00
Re: return Vs break in while loop ; for effeciency   
Feb 19, 2003 1:09 PM (reply 4 of 23)  (In reply to #2 )

 
Me, I would write that like this:
for (final Iterator iterator = vector.iterator(); iterator.hasNext();) {
  final Object obj = iterator.next();
  if (obj.equals(searchObj)) {
    // Stop searching
    return obj;
  }
}
 
// Not found
return null;
I don't have a problem returning from a loop if what I'm doing is reasonably explicit.
Some people prefer to have only one return point where possible, and there's something to be said for that.

It's worth noting that you would need a final return statement anyway, in case the object wasn't found. But in practice this kind of issue is likely to be highly dependent on the rest of the method - I think it's too difficult to generalise this situation. If you need the data later in the method, then you'll have to maintain an external variable. It's quite possible that returning null would not be appropriate here if the object is not found (perhaps I want to throw an Exception), in which case I'd need an if statement later to check to see if a result was returned.
 
pervel
Posts:2,091
Registered: 4/20/97
Re: return Vs break in while loop ; for effeciency   
Feb 19, 2003 2:25 PM (reply 5 of 23)  (In reply to #2 )

 
What if i use Break
actually i forgot tp put the break in th efirst post.
Can any one explain me which of the following two is
more effecient and why.

Repeat exactly the same argument as I made before. The first one is both more efficient and better style.
 
intelligentxjini
Posts:94
Registered: 11/25/02
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 4:50 AM (reply 6 of 23)  (In reply to #5 )

 
What is the significance of Single entry and Single exit. how will it help in making the code effecient

I mean to say if there is only one return statement how will it effect in making the program more effecient.

coz if we use break we do same number of iterations as we do while returning from a loop directly.


Is following the single return statement rule worth.

Please explain
Nas.
 
asquithea
Posts:1,212
Registered: 2/17/00
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 4:59 AM (reply 7 of 23)  (In reply to #6 )

 
Why don't you think about it, draw conclusions, and report what you think?
Then we can flame you if you're wrong.
 
gothboy
Posts:94
Registered: 12/12/02
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 5:08 AM (reply 8 of 23)  (In reply to #6 )

 
What is the significance of Single entry and Single
exit. how will it help in making the code effecient

It doesn't make it more efficient, it makes it easier to understand. With a single entry point (which is unavoidable) and a single exit point, you know exactly where the code starts and ends. When scanning down a method, you don't have to worry about whether or not you might have left the method before you come to some statement or other - if it's execution is not conditional, it must run.

At least, that's what they told me to justify banning the use of multiple return statements in our code where I work; I don't necessarily agree with it myself, but I lost that argument :-)
 
andy.g
Posts:150
Registered: 9/26/00
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 5:09 AM (reply 9 of 23)  (In reply to #6 )

 
What is the significance of Single entry and Single
exit. how will it help in making the code effecient

I mean to say if there is only one return statement
how will it effect in making the program more
effecient.

coz if we use break we do same number of iterations as
we do while returning from a loop directly.


Is following the single return statement rule worth.

Please explain
Nas.

Sing exit point does not help improving performance, but could be a good code style for later maintainence. Say, if you want to add some operation on the returned value, with more than one exit point, you might miss some of the exit points, which could result in a bug. A common rule for a good style is code reusability, same logic should only be written once. With multi-exit-point, any change on the return value could result in repeated logic in the codes (though it's faster).
 
asquithea
Posts:1,212
Registered: 2/17/00
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 5:29 AM (reply 10 of 23)  (In reply to #9 )

 
It's a policy I don't altogether agree with. Making a blanket requirement to have single return points can lead to some convoluted and unnecessarily complicated code. For example:
for (final Iterator sIterator = colA.iterator(); sIterator.hasNext();) {
  final Object obj = sIterator.next();
  if (obj == searchObj) {
    // Found container collection
    return colA;
  }
}
  
for (final Iterator sIterator = colB.iterator(); sIterator.hasNext();) {
  final Object obj = sIterator.next();
  if (obj == searchObj) {
    // Found container collection
    return colB;
  }
}
 
for (final Iterator sIterator = colC.iterator(); sIterator.hasNext();) {
  final Object obj = sIterator.next();
  if (obj == searchObj) {
    // Found container collection
    return colC;
  }
}
 
for (final Iterator sIterator = colD.iterator(); sIterator.hasNext();) {
  final Object obj = sIterator.next();
  if (obj == searchObj) {
    // Found container collection
    return colD;
  }
}
 
// Not found
return null;

... is probably preferable to this...
Collection out = null;
for (final Iterator sIterator = colA.iterator(); sIterator.hasNext();) {
  final Object obj = sIterator.next();
  if (obj == searchObj) {
    // Found container collection
    out = colA;
  }
}
 
if (out != null) {
  for (final Iterator sIterator = colB.iterator(); sIterator.hasNext();) {
    final Object obj = sIterator.next();
    if (obj == searchObj) {
      // Found container collection
      out = colB;
    }
  }
 
  if (out != null) {
    for (final Iterator sIterator = colC.iterator(); sIterator.hasNext();) {
      final Object obj = sIterator.next();
      if (obj == searchObj) {
        // Found container collection
        out = colC;
      }
    }
 
    if (out != null) {
      for (final Iterator sIterator = colD.iterator(); sIterator.hasNext();) {
        final Object obj = sIterator.next();
        if (obj == searchObj) {
          // Found container collection
          out = colD;
        }
      }
    } 
  }
}
 
return out;

I'm not claiming that this is a particularly sensible method; I just wanted to gin up a quick copy and paste. Nonetheless, I have several methods that follow this basic pattern of searching multiple collections in prioritised order.

There is a small gain in efficiency in the first version, but I think the gain in readability is more significant. As previously stated, the first pattern might give trouble if further processing is later added, but from my experience it would be more likely that an additional Collection would be added later in this example, which would be far easier to accomplish using blocked multiple returns.
 
asquithea
Posts:1,212
Registered: 2/17/00
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 5:31 AM (reply 11 of 23)  (In reply to #10 )

 
Ah, whoops. All the if statements should say
if (out == null) {
but I guess that (accidently) makes a small point about maintainability!
 
smg123
Posts:3,660
Registered: 10/24/98
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 5:34 AM (reply 12 of 23)  (In reply to #11 )

 
I was taught "one entry point...one exit point" - but I see your point errrrrr idea.
 
andy.g
Posts:150
Registered: 9/26/00
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 6:23 AM (reply 13 of 23)  (In reply to #10 )

 
It's a policy I don't altogether agree with. Making a
blanket requirement to have single return points can
lead to some convoluted and unnecessarily complicated
code. For example:

I'm not claiming that this is a particularly sensible
method; I just wanted to gin up a quick copy and
paste. Nonetheless, I have several methods that follow
this basic pattern of searching multiple collections
in prioritised order.

There is a small gain in efficiency in the first
version, but I think the gain in readability is more
significant. As previously stated, the first pattern
might give trouble if further processing is later
added, but from my experience it would be more likely
that an additional Collection would be added
later in this example, which would be far easier to
accomplish using blocked multiple returns.

Yep, you got the point, and I actually use return heavily just to avoid ugly block codes. Though I have to point out that your example is a bad example, with a good design, your example can still have one exit point plus a good-looking codes:
// Assume the link list holds all the collections, and enty.value is the current collection, entry.next is the next entry.
public Object lookup(LinkListEntry entry) {
  Collection col = (Collection)entry.value;
  Object obj = null;
  for (final Iterator sIterator = col.iterator(); sIterator.hasNext();) {
    obj = sIterator.next();
    if (obj == searchObj) {    // Found container collection
       break;;
    }
  }
  
  if(obj == null) {
    obj = lookup(entry.next);
  }
  return obj;
}

by doing this, you've got both one-exit point and scalability (which is much better than the original one). So, we should always put code reusability in mind, though I don't mean that we must use single-point exit.
 
intelligentxjini
Posts:94
Registered: 11/25/02
Re: return Vs break in while loop ; for effeciency   
Feb 20, 2003 6:30 AM (reply 14 of 23)  (In reply to #13 )

 
Well deveation from the actual topic but i feel its important to know...

which loop is the effecient way for traversing Iterator
while or for.

ofcourse making iterator final makes it more effecient, but which is
more effecient to use for loop or while loop. ofcourse we will be using break statement. but i hope effeciencycomes into picture in the syntax directed analysis of while and for loop.

i just want to knwo which is more effecient.

Its like... we are using java, and as a developer we should be very much concerned bt effeciency..

Answers please...
 
This topic has 23 replies on 2 pages.    1 | 2 | Next »
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums