On Dec 15, 7:29 pm, "[email protected]" <[email protected]>
wrote:
> Just wondering what is a better way to code. Using for each loops or
> for loops?
>
> I am wondering will the resulting javascript be different.
It first depends whether you're looping on an array or an Iterable<?>.
With an array, GWT compiles the following:
for (Cls obj : arr) { ... }
the same as:
for (int i = 0, l = arr.length; i < l; i++) { ... }
It's faster than:
for (int i = 0; i < arr.length; i++) { Cls obj = arr[i]; ... }
because arr.length is cached.
Iterable<?> are different, because GWT cannot predict how they'll
behave (and Iterable<?> don't have a size, and even Collection<?>
could be modified while iterating), so it always involves getting an
Iterator<?> out of the Iterable<?>, which will probably always be less
performing than iterating by indices if you can.
I haven't checked, but GWT probably compiles the following:
for (Cls obj : iterable) { ... }
the same as:
for (Iterator<Cls> iter = iterable.iterator(); iter.hasNext; ) {
Cls obj = iter.next();
...
}
For anything backed by an array, this will mean the arr.length is
probably checked on each iteration, as well as checks for whether the
iterable was modified within the loop (and throw a
ConcurrentModificationException).
However, Ray Cromwell and others are working on improving this
situation and further optimize for(:) loops on Iterable<?>s under some
conditions on the Iterator/Iterable implementation details.
So my recommendation would be to stick to for(:) loops if they work
for you as they're more readable and less error-prone; and try to work
with arrays if you can.
--
You received this message because you are subscribed to the Google Groups
"Google Web Toolkit" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-web-toolkit?hl=en.