Skip to content

String Micro-Benchmark

I was having a discussion with a colleague a while ago. To whit: which is ‘better’, Groovy’s GString interpolation or simple, brain-dead String concatenation?

In the grandest spirit of discovery, I said: “let’s see.”

A simple Groovy test ‘framework’:

@Grab(group='commons-lang', module='commons-lang', version='2.6')
import org.apache.commons.lang.time.StopWatch

def concatenator = { i ->
  def i2 = i * 2
  def iCubed = Math.pow(i, 3)
  'i == ' + i + '; 2i == ' + i2 + '; i**3 == ' + iCubed
}

def interpolator = { i ->
  def i2 = i * 2
  def iCubed = Math.pow(i, 3)
  "i == ${i}; 2i == ${i2}; i**3 == ${iCubed}"
}

def interpolator2 = { i ->
  "i == ${i}; 2i == ${i * 2}; i**3 == ${Math.pow(i, 3)}"
}

def tmr(c) {
  // warmup
  for(i = 0; i < 100; i ++)
    c.call(i)

  def timerS = new StopWatch()

  timerS.start()

  // work for real
  for(i = 0; i < 10000000; i ++)
    c.call(i)

  timerS.stop()

  timerS.toString()
}

println "Concatenator: ${tmr(concatenator)}"
println "Iterpolator: ${tmr(interpolator)}"
println "Iterpolator2: ${tmr(interpolator2)}"

And the result:

Concatenator: 0:00:16.470
Iterpolator: 0:00:04.406
Iterpolator2: 0:00:04.380

Probably not the most definitive investigation ever but as far as I am concerned: interpolation FTW!

Tags:

C, Java Enterprise Edition, JEE, J2EE, JBoss, Application Server, Glassfish, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, GPars, GAnt, Spock, Gradle, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE, Eclipse, Intellij, Oracle Service Bus, OSB