groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Winnebeck, Jason" <>
Subject RE: For-loop vs each.
Date Wed, 29 Jun 2016 16:08:41 GMT
I’ve never benchmarked it, but I assume foreach is faster because there is no closure class
created or closure instance instantiated, or call on the call stack, plus it probably is easier
for the JVM to optimize/inline the code when the loop is directly in the method. I use compile
static a lot in Groovy and I used to use .each but always prefer the foreach loop now for
the perceived performance difference but also because it runs much nicer in debugger (easier
to step through in IntelliJ IDEA, better stack trace, and easier/faster to hotswap and less
likely of JVM crash when hotswapping). For the extra few characters each saves, it’s not
worth it. That said, I still do use each when I have a closure variable already (like as a
parameter) or want to call a method reference (collection.each a.&b).


From: Schalk Cronjé []
Sent: Wednesday, June 29, 2016 11:50 AM
Subject: For-loop vs each.

This questions is NOT about style, for if it was I would settle for using 'each' all the time.
Np, this time I'm coming from a different angle. I am investigating backwards compatibility
of Gradle plugins written in Groovy.

With Gradle 2.8, the embedded version of Groovy is 2.4.4, whereas with earlier 2.x versions
it is a Groovy 2.3.x version. This leads to an 'interesting' situation where one might compile
a Gradle plugin using Gradle 2.13 and then try to run it with say Gradle 2.1. Let's start
with an example first.

Normally one might do the following:

void method(Set<String> collection)  {
collection.each { println it }
However if that is compiled with Groovy 2.4.x and then run with Groovy 2.3.x it will fail
with NoSuchMethodError. This is usually due to GROOVY-6863. Most people will never see this
as they will not usually go backwards. However in the Gradle situation this is real concern.
So far in all cases that  I have seen I can work around the problem by writing

void method(Set<String> collection)  {
for( String it in collection)  { println it }
This brings me to the question, whether there is any performance problem here or is this a
fine solution?


Schalk W. Cronjé

Twitter / Ello / Toeter : @ysb33r

This email message and any attachments are for the sole use of the intended recipient(s).
Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the
intended recipient, please contact the sender by reply email and destroy all copies of the
original message and any attachments.
View raw message