Groovy performance

Started studying Groovy today. And decided to do some performance testing.

Sum data from 0 to 100000000.

int sum1 = 0;
for(int i = 0; i < 100000000; i++) {   sum1 += i; }

Time: 82 ms

def sum1 = 0
100000000.times { val ->
  sum1 =

Time: 15049 ms

Conclusion: The difference is huge because Groovy does not have primitive types, just the wrappers. So it does boxing/unboxing all the time. You'd better write arithmetic operations on pure Java.

Concatenating char for 100000000 times.

StringBuilder str = new StringBuilder();
for(int i = 0; i < 100000000; i++) {   str.append("a"); }

Time: 1195 ms

def str = 'a' * 100000000;
Time: 3860 ms

Conclusion: The difference is about three times.

Reading 10000000 lines from file.

String str = null;
List data = new ArrayList();
BufferedReader reader = new BufferedReader(new FileReader("test.out"));
while((str = reader.readLine()) != null) {

Time: 15326 ms

def data = new File('test.out').readLines();
Time: 21125 ms

Conclusion: Sounds like the overhead in Groovy is rather small. But what about flexibility? It's really amazing.

Creating 1000000 objects.

for(int i = 0; i < 1000000; i++) {   Book book = new Book();   book.setTitle("Book" + i); }
Time: 273 ms

1000000.times {i ->
  new Book(title: 'Book' + i)

Time: 1816 ms

Conclusion: Dynamic instantiation is quicker in Java.

Adding 10000000 objects to the list.

Book book = new Book();
List data = new ArrayList();
for(int i = 0; i < 10000000; i++) {   data.add(book); }

Time: 300 ms

def books = [];
def book = new Book(title: 'Book')
10000000.times {i ->

Time: 2645 ms

Conclusion: And again Java is quicker.

As you can see pure Java is always faster than Groovy in these simple tests. In case of working with primitives - it's incredibly faster. In the other cases the difference is not so huge. Groovy has really cool features like full integration with Java, closures, additional library methods over the existing Java objects and as result more clean, beautiful and maintainable code. And you pay with the performance of application for these benefits.
In my point of view Groovy nicely fits scripts or small application, when you quickly need to create something simple and don't create million objects at a time. However usage of Groovy could reduce the performance of your big enterprise application.

In any case Groovy is cool and I'm looking forward to use it in the future development, at least for my personal needs.