Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2006

Tip: Looking for answers? Try searching our database.

opting out of Iterators

Thread view: 
Ike - 02 Jan 2006 15:32 GMT
I am constantly trying to write my code (regardless of language) in the
lowest common denominator syntax (I'm too old, I've had to rewrite too much
code in my days! By doing this, conversion of code segments to other similar
languages in the future is far simpler). That is, code that essentially
looks the same in MOST languages (c, c++, php, java, c#). Thus, I try to
avoid, templates, generics, etc.

As such, I also try to avoid Iterators in Java. Say I have

ArrayList arrayList; //will hold String variables

Then I will "iterate," through this as:

for(int x = 0 ; x< arrayList.size(); x++){
   String s = (String)arrayList.get(x);
   // ...
}

Yes, I know that J2SE1.5 allows generics and such (of which I prefer not to
use for the same reasons mentioned earlier) however my real question here
is, since this seemingly more draconian means of iterating through a
collection, as demonstrated here, does, in fact, isuccefully iterate through
just as an Iterator does, am I suffering a sufficient performance hit by
doing so?

TIA, Ike
schulz.stefan@gmail.com - 02 Jan 2006 15:45 GMT
[...]

> As such, I also try to avoid Iterators in Java. Say I have
>
[quoted text clipped - 13 lines]
> just as an Iterator does, am I suffering a sufficient performance hit by
> doing so?

As long as you are using an ArrayList, there really isn't much of a
reason not to use this style (other then the convenience of the
maintainance programmer, that is!), but what if you do not use an
ArrayList, but a more general List, without really knowing the
implementation? It might blow the costs for the loop from n to n².

Also, you lose on type safety by using the raw list type rather then
the generified version. If this is an acceptable tradeoff for having
terser, "more portable" (as in easily rewriteable) code... i am not
going to tell you you are wrong, but i would put the priorities the
other way around.
Paul Bilnoski - 02 Jan 2006 21:56 GMT
> [...]
>
[quoted text clipped - 21 lines]
> ArrayList, but a more general List, without really knowing the
> implementation? It might blow the costs for the loop from n to n².

Since the iterator on a particular List instance is returned as an
interface, it seems implied that it does more than you expect. Not only
for loop performance on iteration alone, but (for example) I've dealt
with smart pointer libraries in C++ where it was smart iterators and
iteration through the list that cleaned up dead references. In
applications where the iterator does more than just dereference and move
 it becomes more important to use them rather than the loop-counter
increment/grab way.

--Paul
Ike - 03 Jan 2006 00:39 GMT
> Since the iterator on a particular List instance is returned as an
> interface, it seems implied that it does more than you expect. Not only
[quoted text clipped - 6 lines]
>
> --Paul

Do you - or anyone who may happen upon this message, know if there is
anything else performed by an Iterator in java like you mention here, which
may not meet the eye? Thanks, Ike
John C. Bollinger - 03 Jan 2006 02:56 GMT
>>Since the iterator on a particular List instance is returned as an
>>interface, it seems implied that it does more than you expect. Not only
[quoted text clipped - 4 lines]
>>  it becomes more important to use them rather than the loop-counter
>>increment/grab way.

> Do you - or anyone who may happen upon this message, know if there is
> anything else performed by an Iterator in java like you mention here, which
> may not meet the eye? Thanks, Ike

I do not think that the iterators of Java's standard List
implementations do anything similar to the behavior Stefan described.
Moreover, I think it broken indeed that any iterator, anywhere, does
that kind of work -- "more than you expect" is never what you want of a
component.  I would consider the particular C++ library Stefan mentioned
to be quite buggy, unless the smart iterators he mentioned were the
*only* way to access list elements.

On the other hand, people can and do write shockingly bad Java code.
(And C++ code just as bad, but it's less shocking :-))  It is entirely
possible that some custom List implementation you run into one day might
play tricks with iterators.  It is up to you whether or not to worry
about it.

Signature

John Bollinger
jobollin@indiana.edu

Stefan Schulz - 03 Jan 2006 06:55 GMT
> >>Since the iterator on a particular List instance is returned as an
> >>interface, it seems implied that it does more than you expect. Not only
[quoted text clipped - 16 lines]
> to be quite buggy, unless the smart iterators he mentioned were the
> *only* way to access list elements.

You fell for a misquote, i did not write what is attributed to me.
Chris Smith - 04 Jan 2006 04:10 GMT
> I do not think that the iterators of Java's standard List
> implementations do anything similar to the behavior Stefan described.
> Moreover, I think it broken indeed that any iterator, anywhere, does
> that kind of work -- "more than you expect" is never what you want of a
> component.

Indeed, but only when it breaks the abstraction.  If the "more then
expected" were to rebalance a balanced tree (assuming, for some odd
reason, that the rebalancing done by Iterator were net beneficial for
performance reasons over that done by get(int)), then I wouldn't see a
problem.  This falls into the same category as the LinkedList issue, of
course.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Roedy Green - 03 Jan 2006 03:20 GMT
>Do you - or anyone who may happen upon this message, know if there is
>anything else performed by an Iterator in java like you mention here, which
>may not meet the eye? Thanks, Ike

If you changed your code from an ArrayList to any other collection,
the code that iterates through the elements is unchanged.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Thomas Hawtin - 03 Jan 2006 11:52 GMT
> Do you - or anyone who may happen upon this message, know if there is
> anything else performed by an Iterator in java like you mention here, which
> may not meet the eye? Thanks, Ike

The extra thing Java iterators do as standard is to make some kind of a
"best effort" attempt to detect concurrent modifications (not
necessarily through a different thread). java.util.concurrent
CopyOnWriteArrayList/CopyOnWriteArraySet work on a consistent copy of
the collection. Other iterators in the same package have other peculiar
contracts.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Thomas Hawtin - 02 Jan 2006 16:33 GMT
> I am constantly trying to write my code (regardless of language) in the
> lowest common denominator syntax (I'm too old, I've had to rewrite too much

I was feeling far too old in the Dartmouth Inn two nights ago. Now all
of a sudden I feel all young again.

> code in my days! By doing this, conversion of code segments to other similar
> languages in the future is far simpler). That is, code that essentially
[quoted text clipped - 11 lines]
>     // ...
> }

Sure you don't want to replace that with?:

    for (String string : list) {
        // ...
    }

Okay, but in C and C++ you would write something completely different
from either of those.

> Yes, I know that J2SE1.5 allows generics and such (of which I prefer not to
> use for the same reasons mentioned earlier) however my real question here
> is, since this seemingly more draconian means of iterating through a
> collection, as demonstrated here, does, in fact, isuccefully iterate through
> just as an Iterator does, am I suffering a sufficient performance hit by
> doing so?

For ArrayList you will probably go slightly faster using a loop counter
rather than an iterator. For small lists, you are doing one less very
small allocation. For large lists, there is one less level of
indirection. When I last tested sometime ago, server/C2 HotSpot mostly
removed the iterator penalty. Client HotSpot was back then significantly
slower, if I had a negligible loop body.

If there is a performance problem, one of my first moves would be to
move the loop into its own private method. HotSpot avoids inlining into
large methods, which can cause problems.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Roedy Green - 03 Jan 2006 03:18 GMT
>for(int x = 0 ; x< arrayList.size(); x++){
>    String s = (String)arrayList.get(x);
>    // ...

On the other paw, there is a lot less visual clutter with:

 for ( String s : arrayList )
 {
 System.out.println( s );
}

The less clutter the lower the odds a typo will bite you.

e.g.

>for(int x = 0 ; x< =arrayList.size(); x++){
>    String s = (String)arrayList.get(x);
>    // ...

>for(int x = 0 ; x< arrayList.size(); x++){
>    String s = arrayList.get(i);
>    // ...

>for(String x = 0 ; x< =arrayList.size(); x++){
>    String s = (String)arrayList.get(x);
>    // ...
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Noodles Jefferson - 04 Jan 2006 02:00 GMT
> I am constantly trying to write my code (regardless of language) in the
> lowest common denominator syntax (I'm too old, I've had to rewrite too much
[quoted text clipped - 13 lines]
>     // ...
> }

int i = 0;

while (i < yourArrayList.size()) {

   String s = (String) yourArrayList.get(i);
   
   i++;
   // not tested

}

> Yes, I know that J2SE1.5 allows generics and such (of which I prefer not to
> use for the same reasons mentioned earlier) however my real question here
[quoted text clipped - 4 lines]
>
> TIA, Ike

Signature

Noodles Jefferson
mhm31x9 Smeeter#29 WSD#30
sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM

NP: "The Road to Chicago" -- Thomas Newman (Road to Perdition
Soundtrack)

"Our earth is degenerate in these latter days, bribery and corruption
are common, children no longer obey their parents and the end of the
world is evidently approaching."
--Assyrian clay tablet 2800 B.C.

Dimitri Maziuk - 04 Jan 2006 05:52 GMT
Ike sez:
...
> for(int x = 0 ; x< arrayList.size(); x++){
>     String s = (String)arrayList.get(x);
[quoted text clipped - 3 lines]
>... am I suffering a sufficient performance hit by
> doing so?

No. Potential performance hit is where you resize an ArrayList:
that requires twice the memory. If you run into that and get the
bright idea of fixing it by using LinkedList instead, your loop
will suddently go from O(n) to O(n^2).

Dima
Signature

Riding roughshod over some little used trifle like the English language is not a
big deal to an important technology innovator like Microsoft. They did just that
by naming a major project dot-Net (".Net").  Before that, a period followed by a
capital letter was used to mark a sentence boundary. --T. Gottfried, RISKS 21.91

bugbear - 04 Jan 2006 10:17 GMT
> I am constantly trying to write my code (regardless of language) in the
> lowest common denominator syntax (I'm too old, I've had to rewrite too much
[quoted text clipped - 13 lines]
>     // ...
> }

If the list were simply that - an instance of a class
that implemented java.util.List, you might
(or might not) get very poor performance.

If the List were an instance of java.util.LinkList
the performance would be horrid, since the get(int) method
for a linked list is NOT constant time, it's O(N),
which means your loop would be O(N^2)

Further, one can have iterators over things which don't
even have a get(int) method.

I use this a lot, since the jakarta Collections package
allows me to do such scrummy things as take the Iterators
for 2 objects (e.g. your ArrayLists) and scrunch
them together to make an Iterator that traverses the 2
Lists consecutively. The point is, the concatenated
object that the Iterator is traversing doesn't even exist
to have a get() performed on it...

http://jakarta.apache.org/commons/collections/api-release/org/apache/commons/col
lections/iterators/IteratorChain.html


   BugBear

   BugBear
Chris Uppal - 04 Jan 2006 11:58 GMT
> I am constantly trying to write my code (regardless of language) in the
> lowest common denominator syntax (I'm too old, I've had to rewrite too
> much code in my days! By doing this, conversion of code segments to other
> similar languages in the future is far simpler).

Presumably, as you get older, the number of re-writes you can anticipate in the
time remaining to you will drop towards zero.  Also (presumably) the value you
place on what little time you have left will grow.  Someday the two curves will
cross, and you'll be able to write normal code like a normal programmer.

I would look forward to that day, if I were you.  I would even anticipate it.

   -- chris


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.