Skip to content

Another (Slightly Surprising) Groovy Micro-Benchmark

Cue some tasty blues: ##Well, I woke up this morning…Had a question I wanted to know…Is a closure def as efficient to call as a method def?##

(OK…I won’t give up my day job to become a famous bluesman…or I wouldn’t give up my day job if I had one…which I don’t…which makes me feel blue…cue a tasty blues riff…)

I set out to find out the answer to the burning question stated above.

I fired up GroovyConsole and wrote exhibit A:

def f = { x ->
}

def start = System.currentTimeMillis()

(1..10000000).each { x-> f x }

println "Finished; ${System.currentTimeMillis() - start}"

Not rocket science!

This runs in about 2590ms.

On to exhibit B:

def f(x) {
}

def start = System.currentTimeMillis()

(1..10000000).each { x-> f x }

println "Finished; ${System.currentTimeMillis() - start}"

ONLY the first line of the script has changed, note.

This takes about 4539ms.

Nearly double the time!

With Groovy 1.6.3/Java 1.6.0_14. In a newly-started instance of GroovyConsole. After the other had been shut down.

I admit to being surprised. I had expected a plain old method call to be much faster than a closure invocation (which I had assumed would involve all sorts of ‘meta’ munging).

The converse is true.

Just goes to show, eh!

I’ll have to get hold of Groovy 1.7 and (try to) use it’s AST viewer to see what is going on (didn’t really help me: the AST tree for the closure version seems simpler, but I don’t know whether than translates to real code…)

As always: don’t read too much into this, it isn’t the end of the world, YMMV, etc., etc.

[edit]
This just in from the always-knowledgeable Dr. Paul King:

The over-simplified…answer: Closures probably have more to do but have been highly optimised in the call site code to match what the JVM JITs/caches really well.

Now I know! Thanks, Paul!

Tags:

Java Enterprise Edition, JEE, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE