title: Groovy : closures significantly slower than methods?
body: <p>While playing with different sort algorithms I was surprised that Groovy closures were performing really poorly. I couldn't find a good answer to this so far, so trying my luck here now ;) Why are Groovy closures so much slower than traditional methods?</p>
  
  <p>Here is a simple example that shows the performance difference. It creates two lists with random numbers and sorts them in reverse order, measuring the sorting time. On my machine and for 10k elements it takes <strong>270ms</strong> using a closure and only <strong>50ms</strong> using the Comparator implementation. </p>
  
  <p>The timings vary a bit based on the distribution of random numbers. Also I tried Groovy 1.7.4 and 1.8.0, seeing slightly better performance with the latter. But the overall picture stays the same: closures perform poorly. </p>
  
  <p>What can I do to improve closure performance? Besides not using closures, of course ;)
  Am I missing something or should one not use closures in groovy if performance counts?</p>
  
  <pre><code>def numberCount = 10000
  def random = new Random()
  def unorderedList1 = (1..numberCount).collect{random.nextInt()}
  def unorderedList2 = (1..numberCount).collect{random.nextInt()}
  def timeit = {String message, Closure cl-&gt;
      def startTime = System.currentTimeMillis()
      cl()
      def deltaTime = System.currentTimeMillis() - startTime
      println "$message: \ttime: $deltaTime"
  }
  
  timeit("compare using closure") {
      def comparator= [ compare: { a,b -&gt; return b &lt;=&gt; a }] as Comparator
      unorderedList1.sort(comparator)
  }
  
  timeit("compare using method") {
      Comparator comparator = new MyComparator()
      unorderedList2.sort(comparator)
  }
  
  class MyComparator implements Comparator {
      int compare(a, b) {return b &lt;=&gt; a}
  }
  </code></pre>