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!
