Monday, June 04, 2018

Fast string concatenation with Groovy

String concatenation is one of most used functions when coding. With Groovy, there are quite a few approaches. This article will focus on different operators. The code to evaluate the performance is given below.
@Grab('com.googlecode.gbench:gbench:0.3.0-groovy-2.0')
import gbench.*

List turns = ((0..1000) as List)*.toString()
new BenchmarkBuilder().run( measureCpuTime:false ) {
   'Dynamic typing <<=' {
    def nums = ""
    turns.each{nums <<= it}
  }
  
  'Dynamic typing +=' {
    def nums = ""
    turns.each{nums += it}
  }
  
  'Static Typing <<=' {
    String nums = ""
    turns.each{nums <<= it}
  }
  
  'Static Typing +=' {
    String nums = ""
    turns.each{nums += it}
  }
}.prettyPrint()
The results are quite interesting. See below.
Options
=======
* Warm Up: Auto 
* CPU Time Measurement: Off

Dynamic typing <<=   52838
Dynamic typing +=   711659
Static Typing <<=   386825
Static Typing +=    647186
To achieve the best performance, we need to use def to declare a String variable, and use the compound operator <<= to perform the concatenation.

No comments:

Post a Comment